window.onload = function () {
    var app = new Vue({
        el: '#app',
        data: {
        }
    });
};

Vue.component('devices_grid', {
    data: function () {
        return {
            devices: [],
            selectedDevice: null,
            advancedModeEnabled: false
        }
    },
    props: ['recurring'],

    template: '<div id="deviceList" >\
                    <div class="row no-select">\
                        <div v-for="(device, index) in devices" class="col-md-12">\
                            <div id="device" class="device-list-item bg-light">\
                                <div class="row">\
                                    <div @click="trigger({ index })" class="col-lg-1 col-md-2 col-sm-2 ellipsis"> \
                                        <span><small class="text-dark">{{ device.sourceType }}</small></span><br>\
                                    </div> \
                                    <div @click="trigger({ index })" class="col-lg-6 col-md-5 col-sm-5 ellipsis"> \
                                        <span class="text-primary nowrap">{{ device.name }}</span>\
                                        <span class="text-secondary nowrap">{{ device.presentSummary }}</span><br>\
                                    </div> \
                                    <div @click="trigger({ index })" class="col-lg-3 col-md-3 col-sm-3 ellipsis"> \
                                        <span class="text-success">{{ device.channelSummary }}</span><br>\
                                    </div> \
                                    <div class="col-lg-2 col-md-2 col-sm-2"> \
                                        <div class="float-right"> \
                                            <span  class="text-secondary">\
                                                <i v-if="normalMode" @click="higherDevicePriority({ index })" class="fas fa-2x fa-angle-up cursor-pointer"></i>&nbsp;&nbsp;\
                                                <i v-if="normalMode" @click="lowerDevicePriority({ index })" class="fas fa-2x fa-angle-down cursor-pointer"></i>\
                                                <span v-if="advancedMode"><button type="button" class="btn btn-primary btn-sm details-button" @click="toggleDevice({ device })">{{ device.toggleAction }}</button></span>\
                                                <span v-if="advancedMode"><button type="button" class="btn btn-primary btn-sm details-button" @click="deleteDevice({ device })">Delete</button></span>\
                                            </span> <br>\
                                        </div> \
                                    </div> \
                                </div>\
                            </div>\
                        </div>\
                    </div>\
                    <div class="modal fade" id="copyChannelsModal" tabindex="-1" role="dialog" aria-labelledby="copyChannelsModalLabel" aria-hidden="true">\
                        <div class= "modal-dialog modal-lg" role="document" >\
                            <div class="modal-content">\
                                <div class="modal-header">\
                                    <h5 class="modal-title">Copy existing channel setup?</h5>\
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">\
                                        <span aria-hidden="true">&times;</span>\
                                    </button>\
                                </div>\
                                <div class="modal-body">\
                                    <p>This capture source hasnt been setup yet, but you have other capture sources of the same type that have been. Would you like to\
                                       copy the configuration and channels from another capture source? <p/>\
                                    <p>Click "No" if you want to configure this capture source differently.</p>\
                                </div>\
                                <div class= "modal-footer">\
                                    <button type="button" @click="copyChannels()" class="btn btn-primary" data-dismiss="modal">Yes</button>\
                                    <button type="button" @click="showSettingsPage()" class="btn btn-secondary" data-dismiss="modal">No</button>\
                                </div>\
                            </div>\
                        </div>\
                    </div>\
                </div>',
    mounted: function () {
        var self = this;
        self.reload();        
    },
    computed: {
        advancedMode: function () {
            var self = this;
            return self.advancedModeEnabled
        },
        normalMode: function () {
            var self = this;
            return !self.advancedModeEnabled
        }
    },
    methods: {
        trigger(args) {            
            var self = this;

            var copyOffered = false;
            selectedDevice = this.devices[args.index];
            if (selectedDevice.channelCount == 0 && selectedDevice.sourceType != "IPTV") {
                // check if this is a new device, that could be copied from an existing device
                var self = this;
                for (var i = 0, len = this.devices.length; i < len; i++) {
                    var device = this.devices[i];
                    if (device.id !== selectedDevice.id) {
                        if (device.sourceType == selectedDevice.sourceType && device.channelCount > 0) {
                            console.log("offer to copy channels");                            
                            $('#copyChannelsModal').modal('show');
                            copyOffered = true;
                            break;
                        }
                    }
                }
            }

            if (copyOffered == false) {
                self.showSettingsPage();
            } 
        },
        lowerDevicePriority(selected) {
            var self = this;
            var cutoff = (self.devices.length - 1); 
            if (selected.index < cutoff) {
                var selectedDevice = this.devices[selected.index];
                var otherDevice = this.devices[selected.index + 1];
                // adjust priority
                var url = 'services/service?method=setting.device.priority&from=' + selectedDevice.id + '&to=' + otherDevice.id;
                $.getJSON(url, function (data) {
                    self.reload();
                });
            }
        },
        higherDevicePriority(selected) {
            var self = this;
            if (selected.index > 0) {
                var selectedDevice = this.devices[selected.index];
                var otherDevice = this.devices[selected.index - 1];
                // adjust priority
                var url = 'services/service?method=setting.device.priority&from=' + selectedDevice.id + '&to=' + otherDevice.id;
                $.getJSON(url, function (data) {
                    self.reload();
                });
            }
        },
        copyChannels() {
            console.log("copy channels");
            var self = this;

            var sourceDevice = null;
            for (var i = 0, len = this.devices.length; i < len; i++) {
                var device = this.devices[i];
                if (device.id !== selectedDevice.id) {
                    if (device.sourceType == selectedDevice.sourceType && device.channelCount > 0) {
                        sourceDevice = device;
                        break;
                    }
                }
            }

            if (sourceDevice != null) {
                // request copy
                var url = 'services/service?method=setting.device.copy&source_id=' + device.id + '&target_id=' + selectedDevice.id;
                $.getJSON(url, function (data) {
                    self.reload();
                });
            }
        },        
        showSettingsPage() {
            var page = selectedDevice.sourceType.replace("-", "").toLowerCase();
            if (page === "dvbt" || page === "dvbc" || page === "atsc" || page === "qam") {
                page = "digital";
            }
            else if (page == "sat>ip") {
                page = "satips";
            }
            else if (page.startsWith("sat>ip")) {
                page = "satip";
            }
            var id = selectedDevice.id;
            var name = selectedDevice.name;
            var url = page + '.html?id=' + id + '&type=' + encodeURIComponent(selectedDevice.sourceType) + '&name=' + encodeURIComponent(name);
            showDevicePage(url);
        },
        reload() {
            var self = this;
            var url = 'services/service?method=setting.devices&format=json';
            $.getJSON(url, function (data) {
                if (data.hasOwnProperty('stat') && data.stat == "Failed") {
                    self.devices = [];
                } else {
                    for (var i = 0, len = data.length; i < len; i++) {
                        var source = data[i];
                        if (source.channelCount > 0) {
                            source.channelSummary = " " + source.channelCount + " channels";
                        }
                        source.presentSummary = "";
                        if (source.enabled == false) {
                            source.presentSummary = " (disabled)";
                        }
                        if (source.present == false) {
                            source.presentSummary += " (unavailable)";
                        }
                        if (source.enabled) {
                            source.toggleAction = "Disable";
                        } else {
                            source.toggleAction = "Enable";
                        }
                    }
                    self.devices = data;
                }
            });
        }, 
        forceRefresh() {
            var self = this;
            var url = 'services/service?method=setting.devices&refresh=true&format=json';
            $.getJSON(url, function (data) {
                for (var i = 0, len = data.length; i < len; i++) {
                    var source = data[i];
                    if (source.channelCount > 0) {
                        source.channelSummary = " " + source.channelCount + " channels";
                    }
                    source.presentSummary = "";
                    if (source.present == false) {
                        source.presentSummary = " (unavailable)";
                    }                    
                }
                self.devices = data;
            });
        },
        showAdvancedMode() {
            var self = this;
            self.advancedModeEnabled = true;            
        },
        showNormalMode() {
            var self = this;            
            self.advancedModeEnabled = false;            
        },
        toggleDevice(args) {
            var self = this;
            var device = args.device;
            var url = 'services/service?method=setting.device.enable&source_id=' + device.id;
            if (device.toggleAction === "Disable") {
                url = 'services/service?method=setting.device.disable&source_id=' + device.id;
            }            
            $.getJSON(url, function (data) {
                self.reload();
            });
        },
        deleteDevice(args) {
            var self = this;  
            var device = args.device;
            var url = 'services/service?method=setting.device.delete&source_id=' + device.id;
            $.getJSON(url, function (data) {                
                self.reload();
            });            
        }
    }
});
