class ExpFormatModel extends ObservableModel {
    constructor(inputNumber) {
        super();

        this.expeditionChannels = new Array();
        this.formatData = new Object();
        this.enableDistribution = true;

        this.init();
    }

    init() {
        var async = new Array();
        var self = this;

        async.push(readSingle("Expedition", "Channels").done(function(channelList) {
            var channelArray = channelList.split(',');

            for (var i = 0; i < channelArray.length; i += 2) {
                self.expeditionChannels.push(
                    { "channel": parseInt(channelArray[i]), "name": channelArray[i+1] }
                )
            }
            self.expeditionChannels.sort(function(a, b) {
                return a.name.localeCompare(b.name);
            });
        }));

        async.push(readSingle("Distribution", "SendChannelNames").done(function(sendChannelNames)
        {
            self.enableDistribution = sendChannelNames == true; 
        }));

        async.push(readSingle("Expedition", "Formats").done(function(formatList) {
            var formatArray = formatList.split(',');
            
            for (var i = 0; i < formatArray.length; i += 3) {
                if ($.isNumeric(formatArray[i])) {
                    self.formatData[parseInt(formatArray[i])] = { format: parseInt(formatArray[i+1]), name: formatArray[i+2] }; 
                }
            }
        }));

        $.when.apply($, async).then(function() {
            self.notifyAll();
        })
    }

    persistData() {
        var async = [];
        var formatString = '';

        for (var channel in this.expeditionChannels) {
            if (this.formatData.hasOwnProperty(channel)) {
                formatString += '' + channel + ',' 
                          + this.formatData[channel].format + ','
                          + this.formatData[channel].name + ',';
            }
        }

        async.push(writeToDatabase([{'section':'Expedition', 'key':'Formats', 'value':formatString.slice(0, -1)}], ''));
        async.push(writeToDatabase([{'section':'Distribution', 'key':'SendChannelNames', 'value':this.enableDistribution}], 'Expedition'));

        return $.when.apply($, async);
    }
}
