const path = require('path');
const window = require('../../../helper/window');
const file = require('../../../helper/file');
const dialog = require('./dialog');
const menu = {};

menu.new = function() {
    window.new(path.join(__dirname, '../../renderer/page/edit/edit.html'), 800, 575);
};

menu.import = function() {
    // Select file on user computer
    const filter = [
        {name: 'JSON', extensions: ['json']},
        {name: 'Markdown', extensions: ['md']}
    ];
    dialog.fileSelector(true, false, filter, (canceled, filepath) => {
        // If the user select one file
        if (canceled) {
            return;
        }
        // Read informations
        const ext = file.getExtension(filepath).toLowerCase();
        const content = file.read(filepath);
        let data = {};
        if (ext === 'md') {
            // Create data from markdown file
            data.id = '_' + Math.random().toString(36).substr(2, 9);
            data.title = path.basename(filepath);
            data.content = content;
        } else {
            data = JSON.parse(content);
            // Check if JSON structure is good
            if (data.id === undefined || data.title === undefined || data.content === undefined) {
                // Error data is invalid
                dialog.error('Données invalides', 'Les données dans le fichier JSON sont invalides. Les données ne peuvent pas être importées');
            }
        }
        // Send informations to main window
        mainWindow.webContents.send('import-card', data);
    });
}

menu.devTool = function (item, focusedWindow) {
    if (focusedWindow) {
        focusedWindow.toggleDevTools()
    }
}

module.exports = menu;