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
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
/**
 * Autosave service for automatically saving projects at regular intervals
 */

import SettingsStore from '../addons/settings-store-singleton.js';

class AutosaveService {
    constructor () {
        this.vm = null;
        this.store = null;
        this.intervalId = null;
        this.enabled = false;
        this.interval = 5; // minutes
        this.showNotifications = true;
        this.onlyWhenChanged = true;
        this.lastSaveTime = 0;
        this.initialized = false;
        this.addonSettingsListener = null;
    }

    /**
     * Check if the service is initialized
     * @returns {boolean} True if initialized
     */
    isInitialized () {
        return this.initialized;
    }

    /**
     * Initialize the autosave service
     * @param {VM} vm - The Scratch virtual machine instance
     * @param {Store} store - The Redux store
     */
    initialize (vm, store) {
        this.vm = vm;
        this.store = store;
        this.initialized = true;
        
        // Load settings from localStorage
        this.loadSettings();
        
        // Listen for Redux settings changes
        store.subscribe(() => {
            const state = store.getState();
            const autosaveState = state.scratchGui.autosave;
            
            // Only apply Redux settings if autosave addon is not enabled
            if (!SettingsStore.getAddonEnabled('autosave')) {
                if (autosaveState.enabled !== this.enabled) {
                    this.setEnabled(autosaveState.enabled);
                }
                if (autosaveState.interval !== this.interval) {
                    this.setInterval(autosaveState.interval);
                }
                if (autosaveState.showNotifications !== this.showNotifications) {
                    this.showNotifications = autosaveState.showNotifications;
                }
            }
        });
        
        // Listen for addon settings changes
        this.addonSettingsListener = (e) => {
            if (e.detail.addonId === 'autosave') {
                this.updateFromAddonSettings();
            }
        };
        SettingsStore.addEventListener('setting-changed', this.addonSettingsListener);
        
        // Initial load from addon settings if enabled
        this.updateFromAddonSettings();
    }

    /**
     * Load settings from localStorage
     */
    loadSettings () {
        try {
            const saved = localStorage.getItem('scratch-autosave-settings');
            if (saved) {
                const settings = JSON.parse(saved);
                this.enabled = settings.enabled || false;
                this.interval = settings.interval || 5;
                this.showNotifications = settings.showNotifications !== false;
                this.onlyWhenChanged = settings.onlyWhenChanged !== false;
            }
        } catch (e) {
            console.warn('Failed to load autosave settings:', e);
        }
    }

    /**
     * Save settings to localStorage
     */
    saveSettings () {
        try {
            const settings = {
                enabled: this.enabled,
                interval: this.interval,
                showNotifications: this.showNotifications,
                onlyWhenChanged: this.onlyWhenChanged
            };
            localStorage.setItem('scratch-autosave-settings', JSON.stringify(settings));
        } catch (e) {
            console.warn('Failed to save autosave settings:', e);
        }
    }

    /**
     * Enable or disable autosave
     * @param {boolean} enabled - Whether autosave should be enabled
     */
    setEnabled (enabled) {
        this.enabled = enabled;
        this.saveSettings();
        
        if (enabled) {
            this.start();
        } else {
            this.stop();
        }
    }

    /**
     * Set the autosave interval
     * @param {number} interval - Interval in minutes
     */
    setInterval (interval) {
        this.interval = Math.max(1, Math.min(60, interval)); // Clamp between 1-60 minutes
        this.saveSettings();
        
        if (this.enabled) {
            this.restart();
        }
    }

    /**
     * Update settings from addon settings
     */
    updateFromAddonSettings () {
        if (SettingsStore.getAddonEnabled('autosave')) {
            const wasEnabled = this.enabled;
            this.enabled = SettingsStore.getAddonSetting('autosave', 'enabled');
            this.interval = SettingsStore.getAddonSetting('autosave', 'interval');
            this.showNotifications = SettingsStore.getAddonSetting('autosave', 'showNotifications');
            this.onlyWhenChanged = SettingsStore.getAddonSetting('autosave', 'saveOnlyWhenChanged');
            
            // Start/stop autosave based on enabled state
            if (this.enabled && !wasEnabled) {
                this.start();
            } else if (!this.enabled && wasEnabled) {
                this.stop();
            } else if (this.enabled) {
                // Restart with new interval if needed
                this.start();
            }
        }
    }

    /**
     * Clean up the service and remove event listeners
     */
    destroy () {
        this.stop();
        if (this.addonSettingsListener) {
            SettingsStore.removeEventListener('setting-changed', this.addonSettingsListener);
            this.addonSettingsListener = null;
        }
        this.initialized = false;
    }

    /**
     * Start the autosave timer
     */
    start () {
        if (this.intervalId) {
            clearInterval(this.intervalId);
        }
        
        if (!this.enabled || !this.vm) return;
        
        const intervalMs = this.interval * 60 * 1000;
        this.intervalId = setInterval(() => {
            this.performAutosave();
        }, intervalMs);
        
        console.log(`Autosave started with ${this.interval} minute interval`);
        
        if (this.showNotifications) {
            this.showNotification(`Autosave enabled - saving every ${this.interval} minutes`);
        }
    }

    /**
     * Stop the autosave timer
     */
    stop () {
        if (this.intervalId) {
            clearInterval(this.intervalId);
            this.intervalId = null;
        }
        
        console.log('Autosave stopped');
    }

    /**
     * Restart the autosave timer (stop and start)
     */
    restart () {
        this.stop();
        this.start();
    }

    /**
     * Check if the project has changes that need saving
     * @returns {boolean} True if project needs saving
     */
    hasProjectChanged () {
        if (!this.onlyWhenChanged) return true;
        
        try {
            const state = this.store.getState();
            return state.scratchGui.projectChanged;
        } catch (e) {
            console.warn('Failed to check project changed state:', e);
            return true; // Default to saving if we can't check
        }
    }

    /**
     * Generate a filename for the autosaved project
     * @returns {string} Generated filename
     */
    generateAutosaveFilename () {
        const now = new Date();
        const timestamp = now.toISOString().replace(/[:.]/g, '-').slice(0, 19);
        
        try {
            const state = this.store.getState();
            const projectTitle = state.scratchGui.projectTitle || 'Untitled';
            return `${projectTitle}_autosave_${timestamp}.sb3`;
        } catch (e) {
            return `Scratch_Project_autosave_${timestamp}.sb3`;
        }
    }

    /**
     * Perform an autosave
     * @returns {Promise<boolean>} True if save was successful
     */
    async performAutosave () {
        if (!this.enabled || !this.vm) {
            return false;
        }
        
        try {
            // Check if we have a project loaded
            if (!this.vm.runtime || !this.vm.runtime.targets || this.vm.runtime.targets.length === 0) {
                console.log('Autosave: No project loaded, skipping save');
                return false;
            }

            // Check if project has changed
            if (!this.hasProjectChanged()) {
                console.log('Autosave: Project unchanged, skipping save');
                return false;
            }

            console.log('Autosave: Starting automatic save...');
            
            if (this.showNotifications) {
                this.showNotification('Saving project...', 'saving');
            }

            // Get project data as blob
            const projectBlob = await this.vm.saveProjectSb3();
            const filename = this.generateAutosaveFilename();
            
            // Create download link and trigger download
            const url = URL.createObjectURL(projectBlob);
            const downloadLink = document.createElement('a');
            downloadLink.href = url;
            downloadLink.download = filename;
            downloadLink.style.display = 'none';
            
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
            
            // Clean up the URL object
            setTimeout(() => URL.revokeObjectURL(url), 1000);
            
            this.lastSaveTime = Date.now();
            
            if (this.showNotifications) {
                this.showNotification(`Project saved as ${filename}`, 'success');
            }
            
            console.log(`Autosave: Successfully saved project as ${filename}`);
            return true;
            
        } catch (error) {
            console.error('Autosave: Failed to save project:', error);
            
            if (this.showNotifications) {
                this.showNotification('Failed to save project automatically', 'error');
            }
            
            return false;
        }
    }

    /**
     * Manually trigger an autosave
     * @returns {Promise<boolean>} True if save was successful
     */
    async saveNow () {
        if (!this.enabled) {
            if (this.showNotifications) {
                this.showNotification('Autosave is disabled. Enable it in File menu first.', 'error');
            }
            return false;
        }
        
        return await this.performAutosave();
    }

    /**
     * Show a notification to the user
     * @param {string} message - The message to show
     * @param {string} type - The type of notification (info, success, error, saving)
     */
    showNotification (message, type = 'info') {
        if (!this.showNotifications) return;
        
        // Create notification element
        const notification = document.createElement('div');
        notification.className = 'autosave-notification';
        notification.textContent = message;
        
        // Add type-specific styling
        if (type === 'success') {
            notification.classList.add('autosave-success');
        } else if (type === 'error') {
            notification.classList.add('autosave-error');
        } else if (type === 'saving') {
            notification.classList.add('autosave-saving');
        }
        
        // Position and style the notification
        Object.assign(notification.style, {
            position: 'fixed',
            top: '80px',
            right: '20px',
            backgroundColor: type === 'error' ? '#f44336' : type === 'success' ? '#4caf50' : '#333',
            color: 'white',
            padding: '12px 20px',
            borderRadius: '8px',
            boxShadow: '0 4px 16px rgba(0, 0, 0, 0.4)',
            zIndex: '10000',
            fontSize: '14px',
            fontFamily: '"Helvetica Neue", Helvetica, Arial, sans-serif',
            maxWidth: '320px',
            wordWrap: 'break-word',
            opacity: '0',
            transform: 'translateX(100%)',
            transition: 'all 0.3s ease'
        });
        
        document.body.appendChild(notification);
        
        // Animate in
        requestAnimationFrame(() => {
            notification.style.opacity = '1';
            notification.style.transform = 'translateX(0)';
        });
        
        // Auto-remove after duration
        const duration = type === 'saving' ? 2000 : 4000;
        setTimeout(() => {
            if (notification.parentNode) {
                notification.style.opacity = '0';
                notification.style.transform = 'translateX(100%)';
                setTimeout(() => {
                    if (notification.parentNode) {
                        notification.parentNode.removeChild(notification);
                    }
                }, 300);
            }
        }, duration);
    }

    /**
     * Get the current autosave status
     * @returns {object} Status information
     */
    getStatus () {
        return {
            enabled: this.enabled,
            interval: this.interval,
            lastSaveTime: this.lastSaveTime,
            showNotifications: this.showNotifications,
            onlyWhenChanged: this.onlyWhenChanged
        };
    }
}

// Create a singleton instance
const autosaveService = new AutosaveService();

export default autosaveService;