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

Vue.component('advanced_record_modal', {
    data: function () {
        return {
            listing: "",
            existingRecurring: null,
            existingRecording: null,
            directories: []
        };
    },    
    template: '<div class="modal fade" id="advancedRecordModal" tabindex="-1" role="dialog" aria-labelledby="advancedRecordModalLabel" aria-hidden="true">\
                    <div class= "modal-dialog modal-lg" role="document" >\
                        <div class="modal-content">\
                            <div class="modal-header">\
                                <h5 class="modal-title" id="advancedRecordModalTitle">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">\
                                <div class="row">\
                                    <div class="col-12">\
                                        <p id="advancedRecordModalPeriod" class="text-light"></p>\
                                        <p id="advancedRecordModalDescription"></p>\
                                    </div>\
                                </div>\
                                <div class="row">\
                                    <div class="form-inline col-12">\
                                        <div class="col-12 form-group extra-vertical">\
                                            <label class="col-lg-3 col-sm-5 col-form-label font-weight-bold" for="name">Recording Type:</label>\
                                            <select id="advancedType" class="custom-select col-lg-6 col-sm-7" data-container="body">\
                                                <option id="recordingOnceOption" value="once">Record Once</option>\
                                                <option value="1">Record Series (NEW episodes)</option>\
                                                <option value="2">Record Series (All Episodes)</option>\
                                                <option value="3">Record Series (Daily, this timeslot)</option>\
                                                <option value="4">Record Series (Weekly, this timeslot)</option>\
                                                <option value="5">Record Series (Monday-Friday, this timeslot)</option>\
                                                <option value="6">Record Series (Weekends, this timeslot)</option>\
                                                <option value="7">Record Series (All Episodes, All Channels)</option>\
                                            </select>\
                                        </div>\
                                    </div>\
                                    <div class="form-inline col-12">\
                                        <div class="col-12 form-group extra-vertical">\
                                            <label class="col-lg-3 col-sm-5 col-form-label font-weight-bold" for="name">Pre-Padding:</label>\
                                            <select id="advancedPrePadding" class="custom-select col-lg-6 col-sm-7" data-container="body">\
                                                <option value="default">Default</option>\
                                                <option value="0">0</option>\
                                                <option value="1">1</option>\
                                            </select>\
                                        </div>\
                                    </div>\
                                    <div class="form-inline col-12">\
                                        <div class="col-12 form-group extra-vertical">\
                                            <label class="col-lg-3 col-sm-5 col-form-label font-weight-bold" for="name">Post-Padding:</label>\
                                            <select id="advancedPostPadding" class="custom-select col-lg-6 col-sm-7" data-container="body">\
                                                <option value="default">Default</option>\
                                                <option value="0">0</option>\
                                                <option value="1">1</option>\
                                            </select>\
                                        </div>\
                                    </div>\
                                    <div class="form-inline col-12">\
                                        <div class="col-12 form-group extra-vertical">\
                                            <label class="col-lg-3 col-sm-5 col-form-label font-weight-bold" for="name">Directory:</label>\
                                            <select id="advancedDirectory" class="custom-select col-lg-6 col-sm-7" data-container="body">\
                                                <option value="default">Default</option>\
                                            </select>\
                                        </div>\
                                    </div>\
                                    <div class="form-inline col-12">\
                                        <div class="col-12 form-group extra-vertical">\
                                            <label class="col-lg-3 col-sm-5 col-form-label font-weight-bold" for="name">Keep:</label>\
                                            <select id="advancedKeep" class="custom-select col-lg-6 col-sm-7" data-container="body">\
                                                <option value="0">All</option>\
                                                <option value="1">1</option>\
                                                <option value="2">2</option>\
                                                <option value="3">3</option>\
                                                <option value="4">4</option>\
                                                <option value="5">5</option>\
                                                <option value="6">6</option>\
                                                <option value="7">7</option>\
                                                <option value="8">8</option>\
                                                <option value="9">9</option>\
                                                <option value="10">10</option>\
                                                <option value="11">11</option>\
                                                <option value="12">12</option>\
                                                <option value="13">13</option>\
                                                <option value="14">14</option>\
                                                <option value="15">15</option>\
                                                <option value="16">16</option>\
                                                <option value="17">17</option>\
                                                <option value="18">18</option>\
                                                <option value="19">19</option>\
                                                <option value="20">20</option>\
                                            </select>\
                                        </div>\
                                    </div>\
                                </div>\
                            </div>\
                            <div class="modal-footer">\
                                <button type="button" class="btn btn-danger" @click="save()" data-dismiss="modal">Save</button>\
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>\
                            </div>\
                        </div>\
                    </div>\
               </div>',
    mounted: function () {
        var self = this;   
        self.loaded = false;

        var url = 'services/service?method=setting.list';
        $.getJSON(url, function (data) {            
            self.directories = data.recordingDirectories.split(",");

            // add directories
            $('#advancedDirectory').empty();
            self.directories.forEach(function (directory) {
                $('#advancedDirectory').append("<option value='" + directory + "'>" + directory + "</option>");
            });
        });
    },
    methods: {
        show(listing) {
            var self = this;   
            this.listing = listing;
            this.existingRecurring = null;

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

            $('#advancedRecordModalTitle').text(listing.name);
            $('#advancedRecordModalDescription').text(listing.description);   

            $('#recordingOnceOption').show();

            // populate pre padding options
            $('#advancedPrePadding').empty();
            $('#advancedPrePadding').append("<option value='default'>Default</option>");
            for (i = 0; i <= 120; i++) {
                $('#advancedPrePadding').append("<option value='" + i + "'>" + i + "</option>");
            }

            // populate post padding options
            $('#advancedPostPadding').empty();
            $('#advancedPostPadding').append("<option value='default'>Default</option>");
            for (i = 0; i <= 120; i++) {
                $('#advancedPostPadding').append("<option value='" + i + "'>" + i + "</option>");
            }


            $('#advancedType').val(2);
            $('#advancedPrePadding').val('default');
            $('#advancedPostPadding').val('default');
            $('#advancedKeep').val('0');
            $('#advancedDirectory').val('Default');

            // 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' });
            $('#advancedRecordModalPeriod').text(period);       
            
            
            // determine appropriate buttons to show
            $('#cancelButton').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') {
                var now = new Date();
                if (episodeEndTime >= now) {
                    $('#recordOnceButton').show();
                    $('#recordSeriesButton').show();
                    $('#recordAdvancedButton').show();
                }                
            } else {
                // only show cancel button for shows already scheduled
                $('#cancelButton').show();
            }           

            // show modal
            $('#advancedRecordModal').modal('show');            
        },
        edit(recurring) {                        
            this.existingRecurring = recurring;
            this.existingRecording = null;
            this.listing = null;

            $('#recordingOnceOption').hide();

            // populate pre padding options
            $('#advancedPrePadding').empty();
            $('#advancedPrePadding').append("<option value='default'>Default</option>");
            for (i = 0; i <= 120; i++) {
                $('#advancedPrePadding').append("<option value='" + i + "'>" + i + "</option>");
            }

            // populate post padding options
            $('#advancedPostPadding').empty();
            $('#advancedPostPadding').append("<option value='default'>Default</option>");
            for (i = 0; i <= 120; i++) {
                $('#advancedPostPadding').append("<option value='" + i + "'>" + i + "</option>");
            }

            // preload settings
            $('#advancedRecordModalTitle').text(recurring.name);
            $('#advancedType').val(recurring.type);
            $('#advancedPrePadding').val(recurring.prePadding);
            $('#advancedPostPadding').val(recurring.postPadding);
            $('#advancedKeep').val(recurring.keep);

            if (recurring.hasOwnProperty("directoryID")) {
                var directory = recurring.directoryID;
                if (directory.startsWith("[")) {
                    directory = directory.substr(1).slice(0, -1);
                }
                $('#advancedDirectory').val(directory);
            }

            // show modal
            $('#advancedRecordModal').modal('show');
        },
        editOneOff(recording) {
            this.existingRecurring = null;
            this.existingRecording = recording;
            this.listing = null;

            $('#recordingOnceOption').show();

            // populate pre padding options
            $('#advancedPrePadding').empty();
            $('#advancedPrePadding').append("<option value='default'>Default</option>");
            for (i = 0; i <= 120; i++) {
                $('#advancedPrePadding').append("<option value='" + i + "'>" + i + "</option>");
            }

            // populate post padding options
            $('#advancedPostPadding').empty();
            $('#advancedPostPadding').append("<option value='default'>Default</option>");
            for (i = 0; i <= 120; i++) {
                $('#advancedPostPadding').append("<option value='" + i + "'>" + i + "</option>");
            }

            // preload settings
            $('#advancedRecordModalTitle').text(recording.name);
            $('#advancedType').val("once");
            $('#advancedPrePadding').val(recording.prePadding);
            $('#advancedPostPadding').val(recording.postPadding);
            $('#advancedKeep').val("1");

            if (recording.hasOwnProperty("directoryID")) {
                var directory = recording.directoryID;
                if (directory.startsWith("[")) {
                    directory = directory.substr(1).slice(0, -1);
                }
                $('#advancedDirectory').val(directory);
            }

            // show modal
            $('#advancedRecordModal').modal('show');
        },
        save() {
            // build up recording request
            var url = "services/service?method=recording.save";    

            // handle recurring
            if ($('#advancedType').val() != "once") {                
                url = "services/service?method=recording.recurring.save";
                url += "&recurring_type=" + $('#advancedType').val()

                // keep
                if ($('#advancedKeep').val() != "all") {
                    url += "&keep=" + $('#advancedKeep').val();
                }                
            }


            if (this.existingRecording != null && $('#advancedType').val() != "once") {
                url += "&remove=true";
            }            


            // existing recurring
            if (this.existingRecurring != null) {                
                url += "&recurring_id=" + this.existingRecurring.id;
            }
            // existing recording
            else if (this.existingRecording != null) {                
                url += "&recording_id=" + this.existingRecording.id;
                if (this.existingRecording.hasOwnProperty("epgEventId")) {
                    url += "&event_id=" + this.existingRecording.epgEventId;
                }
            }
            // event
            else {                                
                url += "&event_id=" + this.listing.id;
            }

            // pre-padding
            if ($('#advancedPrePadding').val() != "default") {
                url += "&pre_padding=" + $('#advancedPrePadding').val();
            }
            // post-padding
            if ($('#advancedPostPadding').val() != "default") {
                url += "&post_padding=" + $('#advancedPostPadding').val();
            }

            // directory
            if ($('#directory_id').val() != "default") {
                url += "&directory_id=" + $('#advancedDirectory').val();
            }

            url += "&format=json";
            
            // schedule recording            
            $.ajax({
                url: url,
                crossDomain: true,
                type: 'get',
                async: true,
                success: function (response, textStatus, xhr) {
                    if (response.stat === "ok") {
                        console.log('Advanced record successful');
                        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);                    
                }
            });            
        }        
    }
});
