const fs = require('fs');
const path = require('path');

class ProjectSettings {
    constructor() {
        this.userDir = path.resolve(__dirname); // Use the directory of the current script
        this.settingsFilePath = path.join(this.userDir, 'projectSettings.json'); // File path for settings
        this.uuid = this.loadOrCreateUUID();
        this.getProjectVars(); // load project variables
        //this url could also be the source of all the configs
        this.cloudAPI = "https://pimmoerman.nl/rdlab/tagcode.app/v2/api";
    }

    loadOrCreateUUID() {
        try {
            if (fs.existsSync(this.settingsFilePath)) {
                const fileContent = fs.readFileSync(this.settingsFilePath, 'utf8');
                if (fileContent.trim()) { // Check if file is not empty
                    try {
                        const jsonContent = JSON.parse(fileContent);
                        if (jsonContent && jsonContent.uuid) {
                            return jsonContent.uuid;
                        } else {
                            throw new Error("Invalid JSON structure");
                        }
                    } catch (parseError) {
                        console.error("Error parsing settings file:", parseError.message);
                    }
                }
                // If the file is empty or invalid, fall back to creating a new UUID
                const newUuid = this.generateUUID();
                this.saveSettings({ uuid: newUuid });
                return newUuid;
            } else {
                // If the file doesn't exist, create a new UUID and save it
                const newUuid = this.generateUUID();
                this.saveSettings({ uuid: newUuid });
                return newUuid;
            }
        } catch (err) {
            console.error("Error handling settings file:", err.message);
            const newUuid = this.generateUUID(); // Fallback
            this.saveSettings({ uuid: newUuid });
            return newUuid;
        }
    }

    saveSettings(settings) {
        try {
            fs.writeFileSync(this.settingsFilePath, JSON.stringify(settings, null, 2), 'utf8');
        } catch (err) {
            console.error("Error saving settings file:", err.message);
        }
    }

    generateUUID() {
        let d = new Date().getTime(); // Timestamp
        let d2 = ((typeof performance !== 'undefined') && performance.now && (performance.now() * 1000)) || 0; // Time in microseconds since page-load or 0 if unsupported
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            let r = Math.random() * 16; // Random number between 0 and 16
            if (d > 0) { // Use timestamp until depleted
                r = (d + r) % 16 | 0;
                d = Math.floor(d / 16);
            } else { // Use microseconds since page-load if supported
                r = (d2 + r) % 16 | 0;
                d2 = Math.floor(d2 / 16);
            }
            return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
    }
        

    getProjectVars() {
        try {
            let settings = {};
            if (fs.existsSync(this.settingsFilePath)) {
                const fileContent = fs.readFileSync(this.settingsFilePath, 'utf8');
                settings = JSON.parse(fileContent);
            }

            // Merge default settings with existing settings
            const defaultVars = {
                uuid: this.uuid, // Ensure UUID is included
                locationId: "1",
                configUrls: {
                    cloud: {
                        units: "https://example.com/api/units",
                        taggcodeAPI: this.cloudAPI,
                    },
                    local: {
                        units: "http://localhost:1880/generalFunctions/datasets/unitData.json",
                        taggcodeAPI: "http://localhost:1880/generalFunctions/datasets/assetData",
                    },
                },
            };

            // Save merged settings back to the file
            const mergedSettings = { ...defaultVars, ...settings };
            this.saveSettings(mergedSettings);

            return mergedSettings;
        } catch (err) {
            console.error("Error loading project variables:", err.message);
            return null; // Fallback if there's an issue
        }
    }
}

module.exports = ProjectSettings;
