/**
 * Class definitions for Expedition Export page.
 * 
 * @category Webserver
 * @package ATProcessor
 * @author Sam Meredith <sam@aandtinstruments.com>
 * @version 0.1
 * 
 */

const cNumUserChannels = 32;

/**
 * Defines fields for export and user configuration
 */
class ExpeditionExportModel extends ObservableModel {
    constructor() {
        super();

        this.export = [];
        this.userConfiguration = [];
    }

    init() {
        let self = this;

        let defaultConfiguration = "0x0000,false,0x0f,0x00";

        $.when(readSection("ATPExport")).done(function(exportSection) {
            let exportData = JSON.parse(exportSection);

            let channelList = exportData.channels.split(",");
            for (let i = 0; i < channelList.length; i += 2)
            {
                self.export.push({
                    fieldId: channelList[i],
                    fieldName: channelList[i + 1]
                });
            }

            for (let i = 0; i < cNumUserChannels; i++)
            {
                let userData = exportData["user" + i] || defaultConfiguration;

                self.userConfiguration[i] = {
                    fieldId : userData.split(',')[0],
                    enabled : userData.split(',')[1] === "true",
                    sender : (userData.split(',')[2] || '0x0f'),
                    instance : (userData.split(',')[3] || '0x00')
                };
            }

            self.notifyAll();
        });
    }

    persistData() {
        var databaseArray = new Array();

        for (let i = 0; i < cNumUserChannels; i++)
        {
            databaseArray.push({ 
                'section' : 'ATPExport',
                'key' : "user" + i,
                value : this.userConfiguration[i].fieldId + ',' + 
                    this.userConfiguration[i].enabled + ',' + 
                    (this.userConfiguration[i].sender || '0x0f') + ',' + 
                    (this.userConfiguration[i].instance || '0x00')
            });
        }

        return writeToDatabase(databaseArray, 'Expedition');
    }
}

/**
 * View -> Model interaction for Expedition Export page
 */
class ExpeditionExportController extends BasicController
{
    constructor(model)
    {
        super(model);
    }

    changeChannel(e)
    {
        let index = $(e.target).attr('data-index');
        const field = $(e.target).val();

        this.model.userConfiguration[index].fieldId = field;
    }

    changeInstance(e)
    {
        let index = $(e.target).attr('data-index');
        const instance = $(e.target).val();

        this.model.userConfiguration[index].instance = instance;
    }

    changeSource(e)
    {
        let index = $(e.target).attr('data-index');
        const sender = $(e.target).find('option:selected').val();

        this.model.userConfiguration[index].sender = sender;
    }

    toggleEnable(e)
    {
        let index = $(e.target).attr('data-index');

        this.model.userConfiguration[index].enabled = 
            $(e.target).prop('checked') ? "true" : "false";
    }
}

/**
 * Handle display for Expedition Export page
 */
class ExpeditionExportView extends BasicView {
    constructor(controller) {
        super(controller);

        this.controller.model.init();
    }

    bindEvents() {
        super.bindEvents();

        $('#export-grid').on('change', 'select[name="field"]', (e) =>
            {
                if (!$('#export-grid').hasClass('advanced'))
                {
                    const index = $(e.target).attr('data-index');
                    $('#export-grid select[name="sender"][data-index="' + index + '"] option[value="15"]').prop('selected', true);
                    $('#export-grid select[name="sender"][data-index="' + index + '"]').change();

                    $('#export-grid input[name="instance"][data-index="' + index + '"]').val(0);
                    $('#export-grid input[name="instance"][data-index="' + index + '"]').change();
                }

                this.controller.changeChannel.call(this.controller, e);
            });
        $('#export-grid').on('change', 'input[name="enable"]', this.controller.toggleEnable.bind(this.controller));
        $('#export-grid').on('change', 'select[name="sender"]', this.controller.changeSource.bind(this.controller));
        $('#export-grid').on('change', 'input[name="instance"]', this.controller.changeInstance.bind(this.controller));

        $('.slider-container input').on('change', () => $('#export-grid').toggleClass('advanced'));
    }

    update(model)
    {
        console.log(model);

        if ($('.slider-container input').is(':checked'))
        {
            $('#export-grid').addClass('advanced');
        };

        // Construct Select Options
        let optionString = '';
        for (let i = 0; i < model.export.length; i++)
        {
            optionString += '<option value="' + model.export[i].fieldId +
                '">' + model.export[i].fieldName + '</option>';
        }

        const senderOptions = '<option value="15" selected>Processor</option>'
            +   '<option value="1">Speed Board</option>'
            +   '<option value="2">Speed/Depth Board</option>'
            +   '<option value="5">Wind Board</option>'
            +   '<option value="10">Analogue Board</option>'
            +   '<option value="11">Fastnet</option>'
            +   '<option value="12">NMEA0183</option>'
            +   '<option value="13">CanBus</option>'
            +   '<option value="14">Main Interface Board</option>'
            +   '<option value="17">DLA2 Board</option>'
            +   '<option value="18">Expedition</option>'
            +   '<option value="34">Modbus</option>'
            +   '<option value="35">Cyclops</option>'
            +   '<option value="37">NMEA Interface</option>'
            +   '<option value="38">DLA3 Board</option>'
            +   '<option value="48">NodeRED</option>';

        for (let i = 0; i < cNumUserChannels; i++)
        {        
            $('#export-grid').append('<div>User ' + i + '</div>');

            // Field select
            let $field = $('<select name="field" data-index="' + i + '">' + optionString + '</select>');
            $field.find('option[value="' + model.userConfiguration[i].fieldId + '"]').prop('selected', true);
            $('#export-grid').append($field);

            // Source select
            let $sender = $('<select name="sender" data-index="' + i + '">' + senderOptions + '</select>');
            $sender.find('option[value="' + model.userConfiguration[i].sender + '"]').prop('selected', true);
            $('#export-grid').append($sender);

            // Instance input
            let instance = parseInt(model.userConfiguration[i].instance);
            $('#export-grid').append('<input name="instance" data-index="' + i + '" type="number" value="' + instance + '">');

            // Enable checkbox
            $('#export-grid').append($('<input>', {
                name : "enable",
                type : "checkbox", 
                checked : model.userConfiguration[i].enabled,
                'data-index' : i
            }));
        }
    }
}
