const {ipcRenderer} = require('electron');

class DataService {

    constructor() {
        // Load data from files
        if (!localStorage.list) {
            this.__load();
        }
    }

    get data() {
        const result = [];
        const list = JSON.parse(localStorage.list);
        for (const element of list) {
            result.push(JSON.parse(localStorage.getItem(element)));
        }
        return result;
    }

    getById(id) {
        const list = JSON.parse(localStorage.list);
        if (list.indexOf(id) !== -1) {
            return JSON.parse(localStorage.getItem(id));
        }
        return null;
    }

    add(id, title, content) {
        // If no id (param id = title and param title = content)
        if (!content) {
            content = title;
            title = id;
            // Generate id
            id = this.__uniqid();
        }
        // Add in list
        const list = JSON.parse(localStorage.list);
        list.push(id);
        localStorage.setItem('list', JSON.stringify(list));
        // Add data
        this.update(id, title, content);
    }

    update(id, title, content) {
        // Set object
        const data = {
            id: id,
            title: title,
            content: content
        }
        // Save
        localStorage.setItem(id, JSON.stringify(data));
        // Refresh cards
        ipcRenderer.send('refresh-card');
    }

    remove(id) {
        if (localStorage.getItem(id)) {
            const data = JSON.parse(localStorage.getItem(id));
            // Confirm dialog
            ipcRenderer.send('confirm-delete', data.title);
            return new Promise(resolve => {
                ipcRenderer.once('delete-card', (event, confirm) => {
                    if (confirm) {
                        // Remove from localStorage
                        localStorage.removeItem(id);
                        // Remove from list
                        const list = JSON.parse(localStorage.list);
                        list.removeItem(id);
                        localStorage.setItem('list', JSON.stringify(list));
                    }
                    resolve(confirm);
                });
            });
        }
    }

    reset() {
        localStorage.clear();
        this.__load();
    }

    /* --- Private methode --- */

    __load() {
        ipcRenderer.send('load-file-data');
        ipcRenderer.once('file-data-loaded', (event, data) => {
            for(const key in data) {
                localStorage.setItem(key, JSON.stringify(data[key]));
            }
        });
    }

    __uniqid() {
        return '_' + Math.random().toString(36).substr(2, 9);
    }

}

module.exports = new DataService();