// ----------------------------------------------
// Beispiel lit-8
// litlist.js
// ----------------------------------------------

// ----------------------------------------------
STUNDENPLAN.MainView_cl = Class.create({
// ----------------------------------------------
    initialize: function () {
        this.viewElement = ".cl_mainView";
        this.viewName = "mainView";
        this.className = "MainView_cl";
        this.storage = new STORAGE.Storage_cl(false);
        this.monthNames = [["Januar", 0], ["Februar", 1], ["März", 2], ["April", 3], ["Mai", 4], ["Juni", 5],
            ["Juli", 6], ["August", 7], ["September", 8], ["Oktober", 9], ["November", 10], ["Dezember", 11]
        ];

        var that = this;
        $.ajax({
            url: 'templates/MainView.html',
            type: 'GET'
        }).done(function (data_opl) {
            $('#page-wrapper').append(data_opl);

            that.reloadView_px();
            that.render_px();

            that.initHandler_p();
        }).fail(function (jqXHR_opl, textStatus_spl) {
            alert("[" + that.className + "] Fehler bei Anforderung: " + textStatus_spl);
        });

        STUNDENPLAN.es_o.subscribe_px(this, this.className);
    },
    reloadView_px: function () {
        var markupYearSelect_s = "";
        var nCurrentMonth = new Date().getMonth();

        //var storage = new STORAGE.Storage_cl(false);
        //var datenModelle = storage.getList_px("monatsuebersicht");

        //var notAccessableMonths = this.extractAllMonths_p(datenModelle);
        for (var nIndex = 0; nIndex < this.monthNames.length; nIndex++) {
            //if (notAccessableMonths.contains(this.monthNames[nIndex][0]))
            //    continue;
            markupYearSelect_s += "<option value='" + this.monthNames[nIndex][0] + "' " + (nCurrentMonth === nIndex ? "selected" : "") + " >" + this.monthNames[nIndex][0] + "</option>";
        }
        $('.cl_monthSelect').html(markupYearSelect_s);

        var markupYearSelect_s = "";
        var nCurrentYear = new Date().getFullYear();
        for (var nIndex = 2010; nIndex < 2020; nIndex++) {
            markupYearSelect_s += "<option value='" + nIndex + "' " + (nCurrentYear === nIndex ? "selected" : "") + " >" + nIndex + "</option>";
        }
        $('.cl_yearSelect').html(markupYearSelect_s);
    },
    notify_px: function (self_opl, message_spl, data_apl) {
        switch (message_spl) {
            case this.className:
                switch (data_apl[0]) {
                    case 'list':
                        switch (data_apl[1]) {
                            case 'refresh':
                                console.log('[' + this.viewElement + '] refresh %o', data_apl);
                                self_opl.render_px(data_apl[2]);
                                break;
                        }
                        break;


                    default:
                        console.log('[' + this.className + '] unbekannte list-Notification: %o', data_apl);
                        break;
                }
                break;
            default:
                console.log('[' + this.className + ']  unbekannte Notification: ' + message_spl);
                break;
        }
    },
    canClose_px: function () {
        return true;
    },
    close_px: function () {
        $(this.viewElement).hide();
    },
    showView_px: function (data_opl) {
        $(this.viewElement).show();
    },
    render_px: function (data_opl) {
        console.log("[" + this.className + "] data_opl: %o", data_opl);

        var nCurrentMonth = new Date().getMonth();
        var nCurrentJahr = new Date().getFullYear();
        var storage = new STORAGE.Storage_cl(false);
        var dataTableManager = new DATAMANAGER.DataTableManager_cl();
        var datenModelle = storage.getList_px("monatsuebersicht");

        console.log("[" + this.className + "] datenModelle aus Clientstorage: %o", datenModelle);

        var currentDatamodel = null;
        if (datenModelle !== null) {

            datenModelle.sort(dynamicSortMultiple("jahr", "nMonat"));
            $('#selectMonat').html("");
            var markupDatenmodelle_s = "";
            for (var nIndex = 0; nIndex < datenModelle.length; nIndex++) {

                if (data_opl === null || data_opl === undefined || data_opl === "") {
                    markupDatenmodelle_s += "<option data-nmonat='" + this.getMonthIndex_p(datenModelle[nIndex].monat) + "' data-monat='" + datenModelle[nIndex].monat + "' data-jahr='" + datenModelle[nIndex].jahr + "' value='" + (datenModelle[nIndex].monat + datenModelle[nIndex].jahr) + "' " + (datenModelle[nIndex].monat === this.monthNames[nCurrentMonth][0] && datenModelle[nIndex].jahr === nCurrentJahr.toString() ? "selected" : "") + " >" + (datenModelle[nIndex].monat + " " + datenModelle[nIndex].jahr) + "</option>";

                    if (currentDatamodel === null) {
                        currentDatamodel = (datenModelle[nIndex].monat === this.monthNames[nCurrentMonth][0] && datenModelle[nIndex].jahr === nCurrentJahr.toString() ? datenModelle[nIndex].daten : null);
                    }
                } else {
                    markupDatenmodelle_s += "<option data-nmonat='" + this.getMonthIndex_p(datenModelle[nIndex].monat) + "' data-monat='" + datenModelle[nIndex].monat + "' data-jahr='" + datenModelle[nIndex].jahr + "' value='" + (datenModelle[nIndex].monat + datenModelle[nIndex].jahr) + "' " + (datenModelle[nIndex].monat === this.monthNames[data_opl.monat][0] && datenModelle[nIndex].jahr === data_opl.jahr.toString() ? "selected" : "") + " >" + (datenModelle[nIndex].monat + " " + datenModelle[nIndex].jahr) + "</option>";

                    if (currentDatamodel === null) {
                        currentDatamodel = (datenModelle[nIndex].monat === this.monthNames[data_opl.monat][0] && datenModelle[nIndex].jahr === data_opl.jahr.toString() ? datenModelle[nIndex].daten : null);
                    }
                }
            }
            $('#selectMonat').html(markupDatenmodelle_s);

            if (currentDatamodel !== null) {
                console.log("[" + this.className + "] Datenmodel gefunden und anzeigen: %o", currentDatamodel);
                $('.cl_uebersicht_tBody').html(dataTableManager.generateHTMLTableByData(currentDatamodel));
            }
        }
    },
    doRender_p: function (data_opl) {
        $('#page-wrapper').append(data_opl);
    },
    initHandler_p: function () {

        console.log("[" + this.className + "] Add events to View.");


        $(this.viewElement).on('click', '.cl_addNewMonth', $.proxy(this.addNewYearMonthDialog, this));
        $(this.viewElement).on('click', '.cl_EditColumn', $.proxy(this.editTableColumn, this));
        $(this.viewElement).on('change', '#selectMonat', $.proxy(this.changeSelctedData, this));

        //Debug
        $(this.viewElement).on('click', '.cl_DEBUG_deleteStorage', function (event) {
            var storage = new STORAGE.Storage_cl(false);
            storage.deleteList_px("monatsuebersicht");

            $('#selectMonat').html("");
            alert("Gelöscht");
            event.preventDefault();
        });
    },
    onClickButtons_p: function (event_opl) {
        var action_s = $(event_opl.target).attr("data-action");
        switch (action_s) {
            case 'add':

                break;
            case 'sub':

                break;
            case 'show':

                break;
        }
        // Weiterleitung und Standardbearbeitung unterbinden
        event_opl.stopPropagation();
        event_opl.preventDefault();

    },
    getMonthIndex_p: function (strName) {
        for (var nIndex = 0; nIndex < this.monthNames.length; nIndex++) {
            if (strName === this.monthNames[nIndex][0])
                return this.monthNames[nIndex][1];
        }
    },
    extractAllMonths_p: function (jsonData) {
        var returnVal = [];
        for (var nIndex = 0; nIndex < jsonData.length; nIndex++) {
            returnVal.push(jsonData[nIndex].monat);
        }
        return returnVal;
    },
    addNewYearMonthDialog: function (event) {
        var that = this;
        BootstrapDialog.show({
            title: 'Neuer Monat',
            message: $('.cl_dialogAddNewMonth').html(),
            buttons: [{
                    label: 'Schließen',
                    action: function (dialogRef) {
                        dialogRef.close();
                    }
                }, {
                    label: 'Speichern',
                    action: function (dialogRef) {
                        var strMonat = dialogRef.getModalBody().find('.cl_monthSelect').val();
                        var strjahr = dialogRef.getModalBody().find('.cl_yearSelect').val();
                        var storage = new STORAGE.Storage_cl(false);
                        var nMonat = new Date().getMonth();
                        var dataTableManager = new DATAMANAGER.DataTableManager_cl();
                        /*this.monthNames = [["Januar", 0], ["Februar", 1], ["März", 2], ["April", 3], ["Mai", 4], ["Juni", 5],
                         ["Juli", 6], ["August", 7], ["September", 8], ["Oktober", 9], ["November", 10], ["Dezember", 11]
                         ];
                         for (var nIndex = 0; nIndex < this.monthNames.length; nIndex++) {
                         if (strMonat === this.monthNames[nIndex][0]) {
                         nMonat = this.monthNames[nIndex][1];
                         break;
                         }
                         }*/
                        nMonat = that.getMonthIndex_p(strMonat);
                        var datensaetze = dataTableManager.generateDefaultTableByMonth_px(nMonat + 1, strjahr);
                        //console.log(datensaetze);
                        storage.addItemList_px("monatsuebersicht", {monat: strMonat, nMonat: nMonat, jahr: strjahr, daten: datensaetze});
                        that.render_px({jahr: strjahr, monat: nMonat});
                        //STUNDENPLAN.es_o.publish_px('MainView_cl', ['list', 'refresh', {jahr: strjahr, monat: nMonat}, null]);
                        dialogRef.close();
                    }
                }]
        });
        event.preventDefault();
    },
    editTableColumn: function (event) {
        /*BootstrapDialog.show({
         title: 'Bearbeiten',
         message: $('.cl_dialogEditItem').html(),
         buttons: [{
         label: 'Schließen',
         action: function (dialogRef) {
         dialogRef.close();
         }
         }, {
         label: 'Speichern',
         action: function (dialogRef) {
         var strMonat = dialogRef.getModalBody().find('.cl_monthSelect').val();
         var strjahr = dialogRef.getModalBody().find('.cl_yearSelect').val();
         var storage = new STORAGE.Storage_cl(false);
         var nMonat = new Date().getMonth();
         var dataTableManager = new DATAMANAGER.DataTableManager_cl();
         this.monthNames = [["Januar", 0], ["Februar", 1], ["März", 2], ["April", 3], ["Mai", 4], ["Juni", 5],
         ["Juli", 6], ["August", 7], ["September", 8], ["Oktober", 9], ["November", 10], ["Dezember", 11]
         ];
         for (var nIndex = 0; nIndex < this.monthNames.length; nIndex++) {
         if (strMonat === this.monthNames[nIndex][0]) {
         nMonat = this.monthNames[nIndex][1];
         break;
         }
         }
         
         var datensaetze = dataTableManager.generateDefaultTableByMonth_px(nMonat + 1, strjahr);
         //console.log(datensaetze);
         storage.addItemList_px("monatsuebersicht", {monat: strMonat, nMonat: nMonat, jahr: strjahr, daten: datensaetze});
         STUNDENPLAN.es_o.publish_px("MainView_cl", ['list', 'refresh', {jahr: strjahr, monat: nMonat}, null]);
         dialogRef.close();
         }
         }]
         });*/
        var element = event.target;
        var nSelectedMonth = $('#selectMonat').find("option:selected").attr("data-nmonat");
        var nSelectedYear = $('#selectMonat').find("option:selected").attr("data-jahr");
        STUNDENPLAN.es_o.publish_px("app", ['show', 'editDayView', {Back: {listener: this.viewName, args: ['show', this.viewName, {jahr: nSelectedYear, monat: nSelectedMonth}]}, Daten: JSON.parse($(element).attr('data-item')), Update: {storagename: 'monatsuebersicht', monat: $(element).attr('data-nmonat'), jahr: $(element).attr('data-jahr'), index: $(element).attr('data-id')}}]);

        event.preventDefault();
    },
    changeSelctedData: function (event) {
        var element = event.target;
        var nSelectedMonth = $(element).find("option:selected").attr("data-nmonat");
        var nSelectedYear = $(element).find("option:selected").attr("data-jahr");
        //STUNDENPLAN.es_o.publish_px("MainView_cl", ['list', 'refresh', {jahr: nSelectedYear, monat: nSelectedMonth}, null]);
        console.log("[MainView_cl] Dataset changed: %o %o", nSelectedMonth, nSelectedYear);
        this.render_px({jahr: nSelectedYear, monat: nSelectedMonth});
        event.preventDefault();
        this.className
    }


});
// EOF