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

Vue.component('manage_channels_grid', {
    data: function () {
        return {            
            items: [],
            channels: [],
            loaded: false,
            selectedGroup: null,
            lastSelectedIndex: -1
        }
    },
    props: ['recurring'],

    template: '<div id="channelsList" >\
                    <div v-if="loadedButNoChannels" class="text-center text-primary">\
                        No channels have been set up. Add your channels on the Settings->Devices page. \
                    </div>\
                    <div v-if="loadedButFiltered" class="text-center text-primary">\
                        No channels match the current channel search filter \
                    </div>\
                    <div v-if="items.length > 0">\
                        <table class="device-channels-table table table-bordered table-responsive-md table-striped text-center">\
                            <tr>\
                                <th class="text-left" width="7%"><input type="checkbox" class="big-checkbox" id="toggleAll" v-on:click.self="toggleAll()"> Number</th>\
                                <th class="text-left" width="13%">Name</th>\
                                <th class="text-left" width="30%">Details</th>\
                                <th class="text-left" width="40%">EPG Source<div class="float-right"><i id="deleteChannels" @click="deleteChannels()" class="fa fa-trash fa-lg"></i></div></th>\
                            </tr>\
                            <tr v-for="(item, index) in items" v-bind:class="{ channelSelected: item.selected }">\
                                <td class="text-left" v-on:click.self="toggle(index, item, $event)"><div class="row"><div class="big-checkbox-padding"><input type="checkbox" id="channelSelected" class="big-checkbox" v-model="item.selected" v-on:click.self="toggle(index, item, $event)"></div> {{ item.channelNumberFormated }}</div></td>\
                                <td class="text-left nowrap" v-on:click.self="toggle(index, item, $event)" >{{ item.channelName }}</td>\
                                <td class="text-left nowrap" v-on:click.self="toggle(index, item, $event)" >{{ item.channelDetails }}</td>\
                                <td class="text-left nowrap" v-on:click.self="toggle(index, item, $event)" >{{ item.channelEPG }}<div class="float-right"><i @click="mapChannel(item)" class="fa fa-wrench"></i></div></td>\
                            </tr>\
                        </table>\
                    </div>\
                </div>',
    mounted: function () {
        var self = this;   
        self.loaded = false;
        self.reload();
    },
    computed: {
        loadedButNoChannels: function () {
            var self = this;
            if (self.channels.length === 0 && self.loaded === true)
                return true;
            return false;
        },
        loadedButFiltered: function () {
            var self = this;
            if (self.items.length === 0 && self.channels.length > 0 && self.loaded === true)
                return true;
            return false;
        }
    },
    methods: {
        toggle(index, channel, e) {
            var self = this;            
            console.log("channel clicked");            

            if (self.selectedGroup == null) {
                if (e != null) {
                    console.log("e.shiftKey=" + e.shiftKey);
                    // handle range select
                    if (e.shiftKey) {
                        if (self.lastSelectedIndex != -1) {
                            var startIndex = (index > self.lastSelectedIndex) ? self.lastSelectedIndex : index;
                            var endIndex = (index > self.lastSelectedIndex) ? index : self.lastSelectedIndex;
                            for (var i = startIndex; i <= endIndex; i++) {
                                self.items[i].selected = true;
                            }
                        }
                    } else if (e.ctrlKey) {
                        self.items[index].selected = true;
                    } else {
                        self.lastSelectedIndex = -1;
                        //if (self.selectedGroup == null) {
                        //    self.clearAll();
                        //}
                        channel.selected = true;
                    }
                }
            } else {
                channel.selected = !channel.selected;
            }

            if (self.selectedGroup != null) {
                // all channels is always selected
                if (self.selectedGroup == "All Channels") {
                    channel.selected = true;
                } else {
                    // let the server know if we need to add or remove a group membership
                    if (channel.selected) {
                        var addMembershipURL = "services/service?method=setting.channel.group&channel_id=" + channel.channelId + "&add=" + encodeURIComponent(self.selectedGroup);
                        $.getJSON(addMembershipURL, function (result) {
                            self.reload();
                        });
                    } else {
                        var removeMembershipURL = "services/service?method=setting.channel.group&channel_id=" + channel.channelId + "&remove=" + encodeURIComponent(self.selectedGroup);
                        $.getJSON(removeMembershipURL, function (result) {
                            self.reload();
                        });
                    }
                }
            } 
            self.lastSelectedIndex = index;
        },
        clearAll() {
            var self = this;
            self.items.forEach(function (channel) {
                channel.selected = false;
            });
        },
        toggleAll() {   
            // all on or all off
            var self = this;
            console.log("toggleAll");
            if (self.items.length > 0) {
                var selected = $("#toggleAll").is(':checked');
                /*
                if (self.selectedGroup == "All Channels") {
                    selected = true;
                }
                */
                self.items.forEach(function (channel) {
                    channel.selected = selected;
                });
            } 
            self.lastSelectedIndex = -1;
        },
        mapChannel(item) {
            console.log("map channel");
            app.__vue__.$refs.channelDetailsModal.showChannelMapping(item);
        },
        deleteChannels() {
            var self = this;

            // get the list of selected channels
            var selectedChannels = "";
            var selectedChannelCount = 0;
            self.items.forEach(function (channel) {
                if (channel.selected) {
                    selectedChannels += channel.channelId + ",";
                    selectedChannelCount++;
                }
            });


            // if no channels are selected, we're going to delete all channels            
            var message = "these " + selectedChannelCount + " channels?";
            if (selectedChannelCount === 1) {
                message = "this channel?";
            }
            // if no channels are selected, we're going to delete all channels
            else if (selectedChannelCount === 0) {
                message = "all channels?";
                selectedChannels = "0";
            }

            if (confirm('Are you sure you want to delete ' + message)) {
                var startScanURL = "services/service?method=setting.channel.delete&channel_id=" + selectedChannels;
                $.getJSON(startScanURL, function (result) {
                    // reload the channel list
                    self.reload();
                    $("#toggleAll").prop('checked', false);
                });
            }     
        },
        reload() {
            var self = this;
            var url = 'services/service?method=channel.list&extras=true'; 

            $.getJSON(url, function (data) {
                self.lastSelectedIndex = -1;
                // default to not selected
                data.channels.forEach(function (channel) {
                    if (self.selectedGroup == null) {
                        channel.selected = false;
                    }
                    else if (self.selectedGroup == "All Channels") {
                        channel.selected = true;
                    }
                    else {
                        if (channel.groups.indexOf(self.selectedGroup) !== -1) {
                            channel.selected = true
                        } else {
                            channel.selected = false;
                        } 
                    }
                });
                self.items = data.channels;
                self.channels = data.channels;
                self.loaded = true;
            }).fail(function (e) {
                console.log("error");
            });
        },
        filter(text) {
            // find the channels that match this search text
            var self = this;
            self.lastSelectedIndex = -1;
            var matches = [];
            text = text.toLowerCase();
            self.channels.forEach(function (channel) {
                if (channel.channelName.toLowerCase().indexOf(text) !== -1) {
                    matches.push(channel);
                }
            });
            self.items = matches;
        },
        selectGroupMembers(groupName) {
            var self = this;
            self.selectedGroup = groupName;

            $("#toggleAll").prop('checked', false);

            // exiting group management, deselect all
            if (groupName == null) {
                self.channels.forEach(function (element) {
                    element.selected = false;
                });
                //$("#deleteChannels").show();
            }
            // 'All Channels' always has all channels
            else if (groupName === "All Channels") {
                self.channels.forEach(function (element) {
                    element.selected = true;
                });
                //$("#deleteChannels").hide();
            }
            // others request list of channels in this group, and select those
            else {
                var matches = [];
                self.channels.forEach(function (channel) {
                    if (channel.groups.indexOf(groupName) !== -1) {
                        channel.selected = true
                    } else {
                        channel.selected = false;
                    }
                });
                //$("#deleteChannels").hide();
            }
        }
    }
});
