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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
/**

 * Persistent Storage Manager

 * 

 * จัดการการบันทึกและโหลดการตั้งค่าทั้งหมด (positions, edits, layouts)

 * รองรับ localStorage และ Export/Import JSON

 * Auto-save ทุก 2-3 วินาที

 * 

 * @author Chahua Development Co., Ltd.

 * @version 2.1.0

 */

export class PersistentStorage {
    constructor() {
        this.currentFilePath = null;
        this.autoSaveInterval = null;
        this.autoSaveDelay = 2000; // 2 วินาที
        this.hasUnsavedChanges = false;
        
        // Storage keys
        this.STORAGE_PREFIX = 'chahua-md-presenter';
        this.POSITIONS_KEY = 'positions';
        this.EDITS_KEY = 'edits';
        this.LAYOUTS_KEY = 'layouts';
        this.SETTINGS_KEY = 'settings';
        
        this.init();
    }

    init() {
        // Listen for changes
        this.setupEventListeners();
        
        // Auto-save on window close
        window.addEventListener('beforeunload', () => {
            if (this.hasUnsavedChanges) {
                this.save();
            }
        });
    }

    /**

     * Setup event listeners สำหรับ auto-save

     */
    setupEventListeners() {
        // Listen for position changes
        document.addEventListener('positionChanged', () => {
            this.hasUnsavedChanges = true;
            this.scheduleAutoSave();
        });

        // Listen for content changes
        document.addEventListener('contentChanged', () => {
            this.hasUnsavedChanges = true;
            this.scheduleAutoSave();
        });

        // Listen for layout changes
        document.addEventListener('layoutChanged', () => {
            this.hasUnsavedChanges = true;
            this.scheduleAutoSave();
        });
    }

    /**

     * กำหนดไฟล์ปัจจุบัน

     * 

     * @param {string} filePath 

     */
    setCurrentFile(filePath) {
        this.currentFilePath = filePath;
    }

    /**

     * สร้าง storage key จาก file path และ slide index

     * 

     * @param {string} filePath 

     * @param {number} slideIndex 

     * @param {string} dataType - 'positions', 'edits', 'layouts', 'settings'

     * @returns {string}

     */
    getStorageKey(filePath, slideIndex = null, dataType = 'positions') {
        const cleanPath = this.sanitizeFilePath(filePath);
        const slideKey = slideIndex !== null ? `:slide-${slideIndex}` : '';
        return `${this.STORAGE_PREFIX}:${cleanPath}${slideKey}:${dataType}`;
    }

    /**

     * Sanitize file path สำหรับใช้เป็น key

     * 

     * @param {string} filePath 

     * @returns {string}

     */
    sanitizeFilePath(filePath) {
        if (!filePath) return 'untitled';
        
        // แปลง path เป็น hash เพื่อให้สั้นลง
        return this.simpleHash(filePath);
    }

    /**

     * Simple hash function

     * 

     * @param {string} str 

     * @returns {string}

     */
    simpleHash(str) {
        let hash = 0;
        for (let i = 0; i < str.length; i++) {
            const char = str.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash;
        }
        return Math.abs(hash).toString(36);
    }

    /**

     * บันทึก positions สำหรับ slide หนึ่ง

     * 

     * @param {string} filePath 

     * @param {number} slideIndex 

     * @param {Object} positions 

     */
    savePositions(filePath, slideIndex, positions) {
        const key = this.getStorageKey(filePath, slideIndex, this.POSITIONS_KEY);
        const data = {
            timestamp: Date.now(),
            filePath,
            slideIndex,
            positions
        };
        
        try {
            localStorage.setItem(key, JSON.stringify(data));
            return true;
        } catch (error) {
            console.error('Failed to save positions:', error);
            return false;
        }
    }

    /**

     * โหลด positions สำหรับ slide หนึ่ง

     * 

     * @param {string} filePath 

     * @param {number} slideIndex 

     * @returns {Object|null}

     */
    loadPositions(filePath, slideIndex) {
        const key = this.getStorageKey(filePath, slideIndex, this.POSITIONS_KEY);
        
        try {
            const data = localStorage.getItem(key);
            if (!data) return null;
            
            const parsed = JSON.parse(data);
            return parsed.positions;
        } catch (error) {
            console.error('Failed to load positions:', error);
            return null;
        }
    }

    /**

     * บันทึก content edits สำหรับ slide หนึ่ง

     * 

     * @param {string} filePath 

     * @param {number} slideIndex 

     * @param {Object} edits 

     */
    saveEdits(filePath, slideIndex, edits) {
        const key = this.getStorageKey(filePath, slideIndex, this.EDITS_KEY);
        const data = {
            timestamp: Date.now(),
            filePath,
            slideIndex,
            edits
        };
        
        try {
            localStorage.setItem(key, JSON.stringify(data));
            return true;
        } catch (error) {
            console.error('Failed to save edits:', error);
            return false;
        }
    }

    /**

     * โหลด content edits สำหรับ slide หนึ่ง

     * 

     * @param {string} filePath 

     * @param {number} slideIndex 

     * @returns {Object|null}

     */
    loadEdits(filePath, slideIndex) {
        const key = this.getStorageKey(filePath, slideIndex, this.EDITS_KEY);
        
        try {
            const data = localStorage.getItem(key);
            if (!data) return null;
            
            const parsed = JSON.parse(data);
            return parsed.edits;
        } catch (error) {
            console.error('Failed to load edits:', error);
            return null;
        }
    }

    /**

     * บันทึก layout settings สำหรับ slide หนึ่ง

     * 

     * @param {string} filePath 

     * @param {number} slideIndex 

     * @param {Object} layout 

     */
    saveLayout(filePath, slideIndex, layout) {
        const key = this.getStorageKey(filePath, slideIndex, this.LAYOUTS_KEY);
        const data = {
            timestamp: Date.now(),
            filePath,
            slideIndex,
            layout
        };
        
        try {
            localStorage.setItem(key, JSON.stringify(data));
            return true;
        } catch (error) {
            console.error('Failed to save layout:', error);
            return false;
        }
    }

    /**

     * โหลด layout settings สำหรับ slide หนึ่ง

     * 

     * @param {string} filePath 

     * @param {number} slideIndex 

     * @returns {Object|null}

     */
    loadLayout(filePath, slideIndex) {
        const key = this.getStorageKey(filePath, slideIndex, this.LAYOUTS_KEY);
        
        try {
            const data = localStorage.getItem(key);
            if (!data) return null;
            
            const parsed = JSON.parse(data);
            return parsed.layout;
        } catch (error) {
            console.error('Failed to load layout:', error);
            return null;
        }
    }

    /**

     * บันทึกทุกอย่างสำหรับไฟล์ปัจจุบัน

     * 

     * @param {Array} allData - Array of {slideIndex, positions, edits, layout}

     */
    saveAll(filePath, allData) {
        let savedCount = 0;
        
        allData.forEach(slideData => {
            const { slideIndex, positions, edits, layout } = slideData;
            
            if (positions) {
                this.savePositions(filePath, slideIndex, positions);
                savedCount++;
            }
            
            if (edits) {
                this.saveEdits(filePath, slideIndex, edits);
                savedCount++;
            }
            
            if (layout) {
                this.saveLayout(filePath, slideIndex, layout);
                savedCount++;
            }
        });
        
        this.hasUnsavedChanges = false;
        return savedCount;
    }

    /**

     * โหลดทุกอย่างสำหรับไฟล์ปัจจุบัน

     * 

     * @param {string} filePath 

     * @param {number} totalSlides 

     * @returns {Array}

     */
    loadAll(filePath, totalSlides) {
        const allData = [];
        
        for (let i = 0; i < totalSlides; i++) {
            const positions = this.loadPositions(filePath, i);
            const edits = this.loadEdits(filePath, i);
            const layout = this.loadLayout(filePath, i);
            
            if (positions || edits || layout) {
                allData.push({
                    slideIndex: i,
                    positions,
                    edits,
                    layout
                });
            }
        }
        
        return allData;
    }

    /**

     * Export ทุกอย่างเป็น JSON file

     * 

     * @param {string} filePath 

     * @param {number} totalSlides 

     * @returns {string} - JSON string

     */
    exportToJSON(filePath, totalSlides) {
        const allData = this.loadAll(filePath, totalSlides);
        
        const exportData = {
            version: '2.1.0',
            exportedAt: new Date().toISOString(),
            filePath,
            totalSlides,
            slides: allData
        };
        
        return JSON.stringify(exportData, null, 2);
    }

    /**

     * Import จาก JSON file

     * 

     * @param {string} jsonString 

     * @returns {boolean}

     */
    importFromJSON(jsonString) {
        try {
            const data = JSON.parse(jsonString);
            
            if (!data.version || !data.slides) {
                throw new Error('Invalid JSON format');
            }
            
            const { filePath, slides } = data;
            
            slides.forEach(slideData => {
                const { slideIndex, positions, edits, layout } = slideData;
                
                if (positions) {
                    this.savePositions(filePath, slideIndex, positions);
                }
                
                if (edits) {
                    this.saveEdits(filePath, slideIndex, edits);
                }
                
                if (layout) {
                    this.saveLayout(filePath, slideIndex, layout);
                }
            });
            
            return true;
        } catch (error) {
            console.error('Failed to import JSON:', error);
            return false;
        }
    }

    /**

     * Download JSON file

     * 

     * @param {string} filePath 

     * @param {number} totalSlides 

     */
    downloadJSON(filePath, totalSlides) {
        const json = this.exportToJSON(filePath, totalSlides);
        const blob = new Blob([json], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        
        const a = document.createElement('a');
        a.href = url;
        a.download = `presentation-settings-${Date.now()}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }

    /**

     * Schedule auto-save

     */
    scheduleAutoSave() {
        if (this.autoSaveInterval) {
            clearTimeout(this.autoSaveInterval);
        }
        
        this.autoSaveInterval = setTimeout(() => {
            this.save();
        }, this.autoSaveDelay);
    }

    /**

     * บันทึกทันที (manual save)

     */
    save() {
        if (!this.hasUnsavedChanges) return;
        
        // Trigger save event
        const event = new CustomEvent('persistentStorageSave', {
            detail: {
                filePath: this.currentFilePath,
                timestamp: Date.now()
            }
        });
        document.dispatchEvent(event);
        
        this.hasUnsavedChanges = false;
    }

    /**

     * ลบข้อมูลสำหรับ slide หนึ่ง

     * 

     * @param {string} filePath 

     * @param {number} slideIndex 

     */
    clearSlide(filePath, slideIndex) {
        const posKey = this.getStorageKey(filePath, slideIndex, this.POSITIONS_KEY);
        const editKey = this.getStorageKey(filePath, slideIndex, this.EDITS_KEY);
        const layoutKey = this.getStorageKey(filePath, slideIndex, this.LAYOUTS_KEY);
        
        localStorage.removeItem(posKey);
        localStorage.removeItem(editKey);
        localStorage.removeItem(layoutKey);
    }

    /**

     * ลบข้อมูลทั้งหมดสำหรับไฟล์หนึ่ง

     * 

     * @param {string} filePath 

     */
    clearFile(filePath) {
        const prefix = `${this.STORAGE_PREFIX}:${this.sanitizeFilePath(filePath)}`;
        
        // หา keys ทั้งหมดที่ตรงกับ prefix
        const keysToRemove = [];
        for (let i = 0; i < localStorage.length; i++) {
            const key = localStorage.key(i);
            if (key.startsWith(prefix)) {
                keysToRemove.push(key);
            }
        }
        
        // ลบทั้งหมด
        keysToRemove.forEach(key => localStorage.removeItem(key));
    }

    /**

     * ลบข้อมูลทั้งหมด

     */
    clearAll() {
        const keysToRemove = [];
        for (let i = 0; i < localStorage.length; i++) {
            const key = localStorage.key(i);
            if (key.startsWith(this.STORAGE_PREFIX)) {
                keysToRemove.push(key);
            }
        }
        
        keysToRemove.forEach(key => localStorage.removeItem(key));
    }

    /**

     * Get storage usage info

     * 

     * @returns {Object}

     */
    getStorageInfo() {
        let totalSize = 0;
        let itemCount = 0;
        
        for (let i = 0; i < localStorage.length; i++) {
            const key = localStorage.key(i);
            if (key.startsWith(this.STORAGE_PREFIX)) {
                const value = localStorage.getItem(key);
                totalSize += key.length + value.length;
                itemCount++;
            }
        }
        
        return {
            itemCount,
            totalSize,
            totalSizeKB: (totalSize / 1024).toFixed(2),
            maxSize: 5120, // 5MB typical localStorage limit
            usagePercent: ((totalSize / (5 * 1024 * 1024)) * 100).toFixed(2)
        };
    }

    /**

     * Cleanup old data (optional)

     * ลบข้อมูลที่เก่ากว่า X วัน

     * 

     * @param {number} daysOld 

     */
    cleanupOldData(daysOld = 30) {
        const cutoffTime = Date.now() - (daysOld * 24 * 60 * 60 * 1000);
        const keysToRemove = [];
        
        for (let i = 0; i < localStorage.length; i++) {
            const key = localStorage.key(i);
            if (!key.startsWith(this.STORAGE_PREFIX)) continue;
            
            try {
                const data = JSON.parse(localStorage.getItem(key));
                if (data.timestamp && data.timestamp < cutoffTime) {
                    keysToRemove.push(key);
                }
            } catch (error) {
                // Invalid JSON, skip
            }
        }
        
        keysToRemove.forEach(key => localStorage.removeItem(key));
        return keysToRemove.length;
    }
}

export default PersistentStorage;