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

Vue.component('listing_details_modal', {
    data: function () {
        return {
            listing: ""
        };
    },    
    template: '<div class="modal fade" id="detailsModal" tabindex="-1" role="dialog" aria-labelledby="detailsModalLabel" aria-hidden="true">\
                    <div class= "modal-dialog modal-lg" role="document" >\
                        <div class="modal-content">\
                            <div class="modal-header">\
                                <h5 class="modal-title" id="detailsModalTitle">Modal title</h5>\
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">\
                                    <span aria-hidden="true">&times;</span>\
                                </button>\
                            </div>\
                            <div class="modal-body details-modal-body">\
                                <div class="row">\
                                    <div class= "col-lg-9 col-md-9 col-sm-9 col-xs-12">\
                                        <p id="detailsModalPeriod"></p>\
                                        <p> \
                                            <span id="detailsModalSubtitle" class="text-dark"></span>\
                                            <span id="detailsModalSeasonEpisode"></span>\
                                            <span id="detailsModalDescription"></span>\
                                        </p> \
                                        <p id="detailsModalGenre"></p>\
                                        <p id="detailsModalFirstRun"></p>\
                                    </div>\
                                    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-10" style="min-width=169px; min-height=243px;">\
                                        <img id="detailsModalImage" class="thumbnail img-fluid" src="" @error="posterError(this);" style="padding: 10px; min-width=169px; min-height=243px;"/>\
                                    </div>\
                                </div>\
                            </div>\
                            <div class="modal-footer">\
                                <div class="mr-auto">\
                                    <button id="recordOnceButton" type="button" class="btn btn-danger" data-dismiss="modal" @click="recordOnce">Record Once</button>\
                                    <button id="recordSeriesButton" type="button" class="btn btn-danger" data-dismiss="modal" @click="recordSeries">Record Series</button>\
                                    <button id="recordAdvancedButton" type="button" class="btn btn-danger" data-dismiss="modal" @click="recordAdvanced">Advanced</button>\
                                    <button id="cancelButton" type="button" class="btn btn-secondary" data-dismiss="modal" @click="cancelRecording">Cancel Recording</button >\
                                    <button id="cancelEpisode" type="button" class="btn btn-secondary" data-dismiss="modal" @click="cancelRecording">Cancel Episode</button >\
                                    <button id="cancelRecurring" type="button" class="btn btn-secondary" data-dismiss="modal" @click="cancelRecurring">Cancel Series</button >\
                                    <button id="watchButton" type="button" class="btn btn-primary" data-dismiss="modal" @click="watchNow" > Watch Now</button >\
                                </div>\
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>\
                            </div>\
                        </div>\
                    </div>\
               </div>',
    mounted: function () {
        var self = this;   
        self.loaded = false;
    },
    methods: {
        show(listing) {
            this.listing = listing;

            var currentTime = (new Date()).getTime() / 1000;
            

            $('#detailsModalTitle').text(listing.name);

            $('#detailsModalSeasonEpisode').text("");
            $('#detailsModalSubtitle').text("");
            $('#detailsModalDescription').text("");
            $('#detailsModalGenre').text("");

            var description = listing.description.replace(listing.subtitle + ":", "");
            var subtitle = listing.subtitle;
            var seasonEpisode = "";
            if (listing.hasOwnProperty("episode") && (listing.episode != 0 || listing.season != 0)) {
                var formattedSeasonEpisode = "S" + this.pad(listing.season, 2) + "E" + this.pad(listing.episode, 2);                
                seasonEpisode = "(" + formattedSeasonEpisode + ")";
                if (subtitle === formattedSeasonEpisode) {
                    subtitle = "";
                }
            }
            $('#detailsModalSeasonEpisode').text(seasonEpisode);   
            $('#detailsModalSubtitle').text(subtitle);             
            $('#detailsModalDescription').text(description);                        

            // period
            var episodeStartTime = new Date(listing.start * 1000);
            var episodeEndTime = new Date(listing.end * 1000);
            var period = '' + episodeStartTime.toLocaleDateString() + '  ' + episodeStartTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) + ' - ' + episodeEndTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
            $('#detailsModalPeriod').text(period);       

            // genre
            if (listing.genres === undefined) {
                $('#detailsModalGenre').text("");
            } else {
                var genre = "";
                for (i = 0; i < listing.genres.length; i++) {
                    if (genre.length > 0) {
                        genre +=", "
                    }
                    genre += listing.genres[i];
                }
                $('#detailsModalGenre').text("[" + genre + "]");
            }

            // first run flag
            if (listing.firstrun) {
                $('#detailsModalFirstRun').text("New Episode");
            } else {
                $('#detailsModalFirstRun').text("");
            }

            // determine appropriate buttons to show
            $('#watchButton').hide();            
            $('#recordOnceButton').hide();
            $('#recordSeriesButton').hide();
            $('#recordAdvancedButton').hide();
            $('#cancelButton').hide();
            $('#cancelEpisode').hide();
            $('#cancelRecurring').hide();

            // only show watch button for shows currently airing
            if (listing.start <= currentTime && listing.end >= currentTime) {
                $('#watchButton').show();
            }
            // only show record button for shows not already scheduled
            if (typeof listing.recording_id === 'undefined') {
                if (listing.id > 0) {
                    var now = new Date();
                    if (episodeEndTime >= now) {
                        $('#recordOnceButton').show();
                        $('#recordSeriesButton').show();
                        $('#recordAdvancedButton').show();
                    }
                }
            } else {
                if (typeof listing.recurring_id === 'undefined') {
                    // only show cancel button for shows already scheduled
                    $('#cancelButton').show();
                }
                else {
                    $('#cancelEpisode').show();
                    $('#cancelRecurring').show();
                }
            }

            // artwork
            $('#detailsModalImage').attr("src", "");
            var artworkURL = 'services/service?method=channel.show.artwork&event_id=' + listing.id;
            $('#detailsModalImage').attr("src", artworkURL);
            $('#detailsModalImage').show();

            // show modal
            $('#detailsModal').modal('show');            

        },
        recordOnce() {
            // request a one off recording
            console.log("record once");
            $.ajax({
                url: 'services/service?method=recording.save&format=json&event_id=' + this.listing.id,
                headers: { "Content-Type": "text/plain" },
                crossDomain: true,
                type: 'get',
                async: true,
                success: function (response, textStatus, xhr) {
                    if (response.stat === "ok") {
                        console.log('A-Ok Record Once' + response);
                        reloadRecordings();                        
                    } else { 
                        //alert("Failed to schedule recording\n\n" + response.msg);
                        showMessage("Scheduling Error", response.msg);
                    }
                },
                error: function (xhr, textStatus, errorThrown) {
                    var message = "Unable to schedule recording at this time. ";
                    if ((xhr.readyState == 4 || xhr.readyState == 0) && xhr.status == 0) {
                        message += "Unable to connect to server.";
                    }
                    showMessage("Scheduling Error", message);                    
                }
            });
        },
        recordSeries() {
            // request scheduling of series recording            
            console.log("record series");            
            $.ajax({
                url: 'services/service?method=recording.recurring.save&format=json&event_id=' + this.listing.id,
                headers: { "Content-Type": "text/plain" },
                crossDomain: true,
                type: 'get',
                async: true,
                success: function (response, textStatus, xhr) {
                    console.log('A-Ok Series Record' + response);                    
                    reloadRecordings();
                },
                error: function (xhr, textStatus, errorThrown) {
                    var message = "Unable to schedule recording at this time. ";
                    if ((xhr.readyState == 4 || xhr.readyState == 0) && xhr.status == 0) {
                        message += "Unable to connect to server.";
                    }
                    showMessage("Scheduling Error", message);
                }
            });            
        },
        recordAdvanced() {            
            $('#detailsModal').modal('hide');
            var modal = app.__vue__.$refs.advancedRecordModal;
            modal.show(this.listing);
        },
        cancelRecording() {
            // request cancellation
            console.log("cancel recording");
            $.ajax({
                url: 'services/service?method=recording.delete&format=json&recording_id=' + this.listing.recording_id,
                headers: { "Content-Type": "text/plain" },
                crossDomain: true,
                type: 'get',
                async: true,
                success: function (response, textStatus, xhr) {
                    console.log('A-Ok Cancel' + response);                    
                    reloadRecordings();
                },
                error: function (xhr, textStatus, errorThrown) {
                    var message = "Unable to cancel recording at this time. ";
                    if ((xhr.readyState == 4 || xhr.readyState == 0) && xhr.status == 0) {
                        message += "Unable to connect to server.";
                    }
                    showMessage("Scheduling Error", message);
                }
            });            
        },
        cancelRecurring() {
            // request cancellation
            console.log("cancel recurring");
            var url = 'services/service?method=recording.recurring.delete&format=json&recurring_id=' + this.listing.recurring_id;
            $.ajax({
                url: url,
                headers: { "Content-Type": "text/plain" },
                crossDomain: true,
                type: 'get',
                async: true,
                success: function (response, textStatus, xhr) {
                    console.log('A-Ok Cancel' + response);
                    reloadRecordings();
                },
                error: function (xhr, textStatus, errorThrown) {
                    var message = "Unable to cancel recurring at this time. ";
                    if ((xhr.readyState == 4 || xhr.readyState == 0) && xhr.status == 0) {
                        message += "Unable to connect to server.";
                    }
                    showMessage("Unable to cancel", message);
                }
            });
        },
        watchNow() {                                    
            window.location.href = 'player.html?channel_id=' + this.listing.channelId;
        },
        posterError(event) {
            $('#detailsModalImage').hide();
        },
        pad(n, width) {
            n = n + '';
            return n.length >= width ? n :
                new Array(width - n.length + 1).join('0') + n;
        } 
    }
});
