requirejs('controls/trackListView');
requirejs('customNodesDefinitions');

window.configInfo = {

    load: function (panel, addon) {
              
        var UI = getAllUIElements(panel);
        
        let LV = UI.lvNodeList;
        LV.controlClass.showHeader = true;
        LV.controlClass.isSortable = false;
        LV.controlClass.multiselect = false;
        LV.controlClass.enableDragNDrop();
    
        let columns = new Array();
        columns.push({
            order: 0,
            width: 80,
            title: _('Type'),
            bindData: function (div, node) {
                if (node.type == 'tracks') {
                    div.innerText = _('Tracks');
                } else if (node.type == 'albums') {
                    div.innerText = _('Albums');
                } else {
                    div.innerText = node.type;
                }
            }
        });
        columns.push({
            order: 1,
            width: 150,
            title: _('Name'),
            bindData: function (div, node) {
                div.innerText = node.name;
            }
        });
        columns.push({
            order: 2,
            width: 300,
            title: _('SQL'),
            bindData: function (div, node) {
                div.innerText = node.sql;
            }
        });
        LV.controlClass.setColumns(columns);

        let nodeDefinitionsArray = getCustomNodeDefinitions(); 
        let list = new ArrayDataSource( nodeDefinitionsArray);
        LV.controlClass.dataSource = list;
        LV.controlClass.setFocusedAndSelectedIndex(0);
       
        UI.editButtons.controlClass.dataSource = list;

        let buttons = UI.editButtons.controlClass.buttons;
        UI.editButtons.controlClass.localListen(buttons.new, 'click', function () {
            let newItem = {
                type: 'tracks',
                name: 'New custom node',
                sql: 'SELECT * FROM Songs WHERE 1=0'
            };
            let dlg = uitools.openDialog('dlgEditCustomNode', {
                item: newItem,
                modal: true,
            });
            dlg.closed = function () {
                if (dlg.modalResult == 1) {
                    list.add(newItem);
                    UI.editButtons.controlClass.updateDisabledState();
                }
            };
            app.listen(dlg, 'closed', dlg.closed);
        });
    
        let _editRule = function (item) {
            let dlg = uitools.openDialog('dlgEditCustomNode', {
                item: item,
                modal: true,
            });
            dlg.closed = function () {     
                if (dlg.modalResult == 1)           
                    LV.controlClass.invalidateAll();                
            };
            app.listen(dlg, 'closed', dlg.closed);
        }
        
        UI.editButtons.controlClass.localListen(buttons.edit, 'click', () => {    
            list.locked( () => {
                let item = list.getValue( list.focusedIndex);
                _editRule(item);
            });
        });
    
        LV.controlClass.localListen(LV, 'itemdblclick', (e) => {
            _editRule(e.detail.item);
        });    

        UI.btnImport.controlClass.localListen( UI.btnImport, 'click', () => {
            var promise = app.utils.dialogOpenFile( app.devices.getExportProfileFolder(), 'mcnc', _('MediaMonkey Custom Nodes Configuration file (*.mcnc)|*.mcnc'), _('Select MediaMonkey Custom Nodes Configuration file'));
            promise.then(function (filename) {
                if (filename != '') {
                    app.filesystem.loadTextFromFileAsync(filename).then( (txt) => {

                        let resArray;
                        try {
                            resArray = JSON.parse(txt);
                        } catch (err) {                     
                            messageDlg( 'Parsing has failed: ' + err, 'Error', ['btnOK'], {
                                defaultButton: 'btnOK'
                            }, undefined);
                            return;
                        }
                        
                        list.clear();
                        for (let i = 0; i < resArray.length; i++) {
                            list.add(resArray[i]);
                        }
                        LV.controlClass.invalidateAll();                    
                    });                    
                }
            });
        });

        UI.btnExport.controlClass.localListen( UI.btnExport, 'click', () => {            
            var promise = app.utils.dialogSaveFile( app.devices.getExportProfileFolder(), 'mcnc', _('MediaMonkey Custom Nodes Configuration file (*.mcnc)|*.mcnc'), _('Save as'), 'myExportedFile.mcnc');
            promise.then((filename) => {
                if (filename != '') {
                    let resArray = this.getConfigurationArray(panel);
                    let json = JSON.stringify(resArray);
                    app.filesystem.saveToFileAsync(filename, json, json.length);                    
                }
            });                                 
        });

    },

    getConfigurationArray: function (panel) {
        let UI = getAllUIElements(panel);
        let DS = UI.lvNodeList.controlClass.dataSource;
        let resArray = [];
        DS.locked( () => {
            for (let i = 0; i < DS.count; i++) {
                let item = DS.getValue(i);
                resArray.push(item);
            }
        });
        return resArray;
    },

    save: function (panel, addon) {        
        let resArray = this.getConfigurationArray(panel);        
        app.setValue('customNodesDefinitions', resArray);
    }
}
