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

Vue.component('recordings_grid', {
    data: function () {        
        return {
            viewType: String,
            summaryWithTitle: Boolean,
            listItems: [],
            gridItems: [], 
            group: null,
            cancelledRecording: null,
            showNewIndicator: false
        }
    },
    props: {
        list: String,
        view: String,        
    },

    template: '<div id="recordingsList" >\
                    <div>\
                        <div v-for="(item, index) in listItems" class="col-12 row-no-padding">\
                            <div id="recording" v-bind:class="getClass(item)">\
                                <div class="row" @click="trigger({ index })">\
                                    <div class="col-sm-7 col-xs-12">\
                                        <span class="text-primary">{{ item.name }}</span>\
                                        <small class="text-light"> {{ item.subtitle }}</small><br>\
                                    </div>\
                                    <div class="col-sm-5 col-xs-12">\
                                        <div class="float-sm-right">\
                                            <span class="text-dark">[{{ item.channel }}] {{ item.period }}</span>&nbsp;\
                                        </div>\
                                    </div>\
                                </div>\
                                <div class="row">\
                                    <div class="col-md-8 col-lg-9" @click="trigger({ index })">\
                                        <span class="text-secondary"> \
                                            <span v-if="showFailed(item)" class= "text-danger text-uppercase">{{ item.status }} </span >\
                                            <span v-if="showRecording(item)" class= "text-warning text-uppercase">{{ item.status }} </span >\
                                            <span v-if="showPending(item)" class= "text-success text-uppercase">{{ item.status }} </span >\
                                            <span class="text-dark">{{ item.subtitleSeason }}</span>{{ item.desc }}\
                                            <span v-if="showFailed(item)" class="text-danger"><br/>{{ item.failedStatus }} </span>\
                                        </span>\
                                    </div>\
                                    <div class="col-md-4 col-lg-3">\
                                        <div class="text-center float-right">\
                                            <span v-if="showPlay(item)"><button type="button" class="btn btn-primary btn-sm details-button" @click="trigger({ index })({ index })">Play</button></span>\
                                            <span v-if="showResume(item)"><button type="button" class="btn btn-primary btn-sm details-button" @click="resume({ index })">Resume</button></span>\
                                            <div class="text-center float-right">\
                                                <span v-if="showDelete(item)"><button type="button" class="btn btn-primary btn-sm details-button" @click="deleteRecording({ index })">Delete</button></span>\
                                                <span v-if="showCancel(item)"><button type="button" class="btn btn-primary btn-sm details-button" @click="deleteRecording({ index })">Cancel</button></span>\
                                                <span v-if="showDownload(item)"><button type="button" class="btn btn-primary btn-sm details-button" @click="download({ index })"><i class="fas fa-download"></i></button></span>\
                                            </div>\
                                            <br >\
                                        </div>&nbsp\
                                    </div>\
                                </div>\
                            </div>\
                        </div>\
                    </div>\
                    <div class="row">\
                        <div v-for="(item, index) in gridItems" class="col-lg-2 col-sm-3 col-4 row-no-padding focusable">\
                            <div id="recording" @click="trigger({index})" class="recording-grid-item bg-light">\
                                <div class="thumbnail-container">\
                                    <img class="thumbnail img-fluid" :src="item.artwork" onerror="coverLoadError(this);">\
                                </div>\
                                <div v-if="showPeriod" class="caption-btm text-center">\
                                    <p>{{ item.name }}<br><span class="text-secondary">{{ item.readableTime }}</span></p>\
                                </div>\
                                <div v-if="showPeriod == false" class="caption-btm text-center">\
                                    <p>{{ item.name }}</p>\
                                </div>\
                            </div>\
                        </div>\
                    </div>\
                </div>',

    mounted: function () {
        var self = this;        

        self.summaryWithTitle = false;
        if (self.list === "pendingSummary")
            self.summaryWithTitle = true;

        var url = 'services/service?method=setting.get&key=/Settings/General/ShowNewInGuide';
        $.getJSON(url, function (data) {
            if (data.value == "true") {
                self.showNewIndicator = true;
            }
        });

        if (self.list === null) {
            self.list = "all";
        }
        if (self.view === null) {
            if (self.list === "all") {
                self.viewType = "grid";
            } else {
                self.viewType = "list";
            }
        } else {
            self.viewType = self.view;
        }
        if (self.list !== "none") {
            self.showFilteredList(self.list);
        }

        window.addEventListener('resize', function () {
            self.handleResize();
        });
    },
    computed: {
        showPeriod: function () {
            return this.summaryWithTitle;
        }
    },
    methods: {
        getClass(listing) {
            var self = this;
            if (self.showNewIndicator === true && (listing.status === "pending" || listing.status === "recording") && listing.firstrun)
                return 'recording-list-item bg-light new-listing-lg';
            else
                return 'recording-list-item bg-light';
        },
        trigger(args) {            
            if (this.gridItems.length > 0) {
                var group = this.gridItems[args.index].name;
                var id = this.gridItems[args.index].id;
                window.location.href = 'details.html?group=' + encodeURIComponent(group) + '&recording_id=' + id;
            }
            else if (this.filter === "pending") {                
                var pending = this.listItems[args.index];
                if (pending.recurringParent > 0) {
                    if (window.eventBus != null) {
                        window.eventBus.$emit('editRecurringParent', pending);
                    }
                } else {
                    if (window.eventBus != null) {
                        window.eventBus.$emit('editRecording', pending);
                    }
                }
            }
            else if (this.viewType === "list") {
                var status = this.listItems[args.index].status;
                var recordingId = this.listItems[args.index].id;
                if (status === "ready" || status === "recording") {
                    var title = this.listItems[args.index].name;
                    window.location.href = 'player.html?recording_id=' + recordingId + "&title=" + encodeURIComponent(title);;
                }
            }
        },
        download(args) {
             if (this.viewType === "list") {
                var status = this.listItems[args.index].status;
                var recordingId = this.listItems[args.index].id;
                if (status === "ready") {
                    var title = this.listItems[args.index].name;
                    window.location.href = 'download?recording_id=' + recordingId;
                }
            }
        },
        resume(args) {
            if (this.viewType === "list") {
                var recording = this.listItems[args.index];
                var status = recording.status;
                var recordingId = recording.id;
                if (status === "ready" || status === "recording") {
                    var title = recording.name;
                    window.open('player.html?recording_id=' + recordingId + "&title=" + encodeURIComponent(title) + "&resume=" + recording.playbackPosition);                    
                }
            }
        },
        handleResize() {
            var captionWidth = $(".caption-btm").width();
            var captionHeight = $(".caption-btm").height();
            var artworkHeight = ((captionWidth / 16) * 9);
            var recordingHeight = artworkHeight + "px";
            $(".thumbnail-container").css("min-height", recordingHeight);                
        },
        showFailed(recording) {
            if (recording.status === "failed") {
                return true;
            }
            return false;
        },
        showPending(recording) {
            if (recording.status === "pending") {
                return true;
            }
            return false;
        },
        showRecording(recording) {
            if (recording.status === "recording") {
                return true;
            }
            return false;
        },
        showPlay(recording) {
            if (recording.status === "ready" || recording.status === "recording")
                return true;
            return false;
        },
        showDownload(recording) {
            if (recording.status === "ready")
                return true;
            return false;
        },
        showResume(recording) {
            return recording.hasOwnProperty("playbackPosition");
        },
        showCancel(recording) {            
            return !this.showDelete(recording);
        },
        showDelete(recording) {
            if (recording.status === "ready" || recording.status === "failed") {
                return true;
            }
            return false;
        },
        deleteRecording(args) {
            var recording = this.listItems[args.index];
            var self = this;
            var url = 'services/service?method=recording.delete&recording_id=' + recording.id + '&format=json';
            $.getJSON(url, function (data) {     
                if (recording.status == "recording") {
                    self.cancelledRecording = recording;
                }

                if (self.group != null) {
                    self.showNamedList(self.group);
                } else {
                    self.showFilteredList(self.filter);
                }

                if (window.eventBus != null) {
                    window.eventBus.$emit('recordingDeleted', data);
                }
            });
        },
        reload() {
            var self = this;
            if (self.group != null) {
                self.showNamedList(self.group);
            } else {
                self.showFilteredList(self.filter);
            }
        },
        showFilteredList(filter) {
            this.filter = filter;
            if (filter === "recent") {
                this.viewType = "list";
            }
            var self = this;
            var url = 'services/service?method=recording.list&filter=' + filter + '&format=json';
            $.getJSON(url, function (data) {
                // add artwork url for easy access from template
                data.recordings.forEach(function (recording) {

                    // fix up for async cancel, that may happen soon after (for cleaner reaction in the web app)
                    if (self.cancelledRecording != null) {                        
                        if (recording.id === self.cancelledRecording.id) {
                            recording.status = "ready";
                        }                                                
                    }

                    recording.artwork = "services/service?method=recording.artwork&landscape=true&with_placeholder=true&recording_id=" + recording.id;

                    // manual recordings dont have a subtitle
                    if (recording.hasOwnProperty("subtitle") == false) {
                        recording.subtitle = "";
                    }

                    // also add period text
                    var startTime = new Date(recording.startTime * 1000);
                    var duration = recording.duration;
                    var endTime = new Date(startTime.getTime() + 1000 * duration);
                    recording.period = startTime.toLocaleDateString() + ' ' + startTime.toLocaleTimeString() + ' - ' + endTime.toLocaleTimeString();
                    recording.readableTime = startTime.toLocaleDateString() + ' ' + startTime.toLocaleTimeString();

                    if (recording.subtitle != "") {
                        recording.subtitleSeason = recording.subtitle + ": "; 
                    }
                    

                    // also failure reason
                    recording.failedStatus = "";
                    if (recording.status === "failed") {
                        recording.failedStatus = " [Failed: " + recording.reason + "]";
                    }

                    // pending indicator
                    recording.pendingStatus = "";
                    if (recording.status === "pending") {
                        recording.failedStatus = "[Pending] ";
                    } else if (recording.status === "recoridng") {
                        recording.failedStatus = "[Recording] ";
                    }
                });

                var added = [];

                // store list/grid
                if (filter === "failed") {
                    self.listItems = data.recordings;
                    self.gridItems = [];
                }
                else if (filter === "all" || filter === "ready" || self.viewType === "grid") {
                    self.listItems = [];
                    self.gridItems = [];


                    if (filter === "ready") {    
                        var groups = [];
                        data.recordings.forEach(function (element) {
                            if (groups.includes(element.name) === false) {                                
                                groups.push(element.name);
                            }
                        });
                        groups.sort();

                        var sorted = [];
                        groups.forEach(function (showName) {
                            data.recordings.forEach(function (unsortedElement) {
                                if (unsortedElement.name === showName) {
                                    sorted.push(unsortedElement);
                                }
                            });
                        });

                        self.listItems = sorted;
                    }
                    else {

                        // in 'ready' mode, we only want each recording listed once                    
                        data.recordings.forEach(function (element) {
                            if (added.includes(element.name) === false) {
                                added.push(element.name);
                                self.gridItems.push(element);
                            }
                        });

                        // sort into alphabetical order
                        added.sort();
                        var sorted = [];
                        added.forEach(function (showName) {
                            self.gridItems.forEach(function (unsortedElement) {
                                if (unsortedElement.name === showName) {
                                    sorted.push(unsortedElement);
                                }
                            });
                        });
                        self.gridItems = sorted;
                        //self.gridItems = data.recordings;
                    }                                    
                } else if (filter === "pendingSummary") {
                    self.listItems = [];
                    self.gridItems = [];

                    // a brief summarized list of what's coming up

                    // in 'ready' mode, we only want each recording listed once                    
                    data.recordings.forEach(function (recording) {
                        if (added.includes(recording.name) === false) {
                            added.push(recording.name);
                            self.gridItems.push(recording);
                        }
                    });

                } else {
                    self.listItems = data.recordings;
                    self.gridItems = [];
                }

                self.handleResize();
            });
        },

        showNamedList(name) {
            var self = this;

            self.filter = "all";
            self.viewType = "list";
            self.group = name;

            var url = 'services/service?method=recording.list&filter=all&format=json';
            $.getJSON(url, function (data) {
                self.gridItems = [];
                self.listItems = [];

                // add artwork url for easy access from template
                data.recordings.forEach(function (recording) {
                    recording.artwork = "services/service?method=recording.artwork&landscape=true&with_placeholder=true&recording_id=" + recording.id;

                    // also add period text
                    var startTime = new Date(recording.startTime * 1000);
                    var duration = recording.duration;
                    var endTime = new Date(startTime.getTime() + 1000 * duration);
                    recording.period = startTime.toLocaleDateString() + ' ' + startTime.toLocaleTimeString() + ' - ' + endTime.toLocaleTimeString();
                    recording.readableTime = startTime.toLocaleDateString() + ' ' + startTime.toLocaleTimeString();

                    recording.failedStatus = "";
                    if (recording.status === "failed") {
                        recording.failedStatus = " [Failed: " + recording.reason + "]";
                    }

                    if (recording.hasOwnProperty("subtitle") == false) {
                        recording.subtitle = "";                        
                    }

                    if (recording.subtitle != "") {
                        recording.subtitleSeason = recording.subtitle + ": ";
                    }

                    recording.pendingStatus = "";
                    if (recording.status === "pending") {
                        recording.pendingStatus = "[Pending] ";
                    } else if (recording.status === "recording") {
                        recording.pendingStatus = "[Recording] ";
                    }

                    if (recording.name === name) {
                        self.listItems.push(recording);
                    }
                });

                if (self.listItems.length == 0) {
                    history.go(-1);
                    return;
                }
            });
        }
    }
});
