//SCREEN-BOILERPLATE

//this boilerplate builds screens that are gonna be shown in the <div class='content'> tag of our main HTML.
//do not build app components with this boilerplate, only screens (reports)

define([
    // Application variable, always include it to have access to app methods.
    'app',

    //templates-loader: this loads templates async.
    'js/templates-loader',

    "modules/DatetimeControl",
],

function (app, T, DatetimeControl) {

    function callSystemTimeConfigurationService(action, options) {
        if (!options)
            options = {};
        if (!options.data)
            options.data = {};

        _.extend(options.data, { action: action, });

        var ajaxOpt = {
            async: true,
            type: 'POST',
        };

        _.extend(ajaxOpt, options);

        $.ajax(app.foldersRoot + '/landing/initConfig/api/systemInitialConfiguration.aspx', ajaxOpt);
    }

    //replace all 'SystemTimeConfiguration' with your view's name.
    var SystemTimeConfiguration = {
        Models: {},
        Views: {},
        //EditionModes: {
        //    Editable: 0,
        //    NotEditable: 
        //},
    }

    SystemTimeConfiguration.Models.Main = Backbone.Model.extend({
        superClass: null,

        defaults: {
            datetime: null,
            date: null,
            time: null,
            syncWithInternetEnabled: false,
            timeZoneId: null,
        },
    });

    //the generate id method is called everytime a view is going to be shown by the router and returns and id that
    //is used by the router to store in cache (if it is cacheable) and to know the current shown view.
    //this is useful in case your view is reusable, and displays different data depending on url parameters 
    //(such as a catalog view, or a report that doesnt change in terms of UI but it does change in terms of data)
    //so you can always use the same view on the router but the cache can tell which view is which by using differents ids.
    SystemTimeConfiguration.generateID = function (viewParams) {
        try {
            //if the viewparams change the view id, then evaluate the viewparams here
            //and return the appropiate id.
            return 'system-time-configuration'; 
        } catch (Error) { }
    }

    SystemTimeConfiguration.Views.Main = Backbone.View.extend({
        template: 'system-time-configuration',
        id: 'system-time-configuration',
        title: '',
        //default not cacheable, change this if you want the view to be cacheable
        // if the view is set as cacheable should also have a refresh method to reset the view without erasing the DOM.
        events: {
            'click #sync_time_ckx': 'syncTimeCkx_click',
            'change #time_zone_cbx': 'timeZoneCbx_change',
        },
        isCacheable: true,
        //templateCompiler: null,
        container: null,
        datetimePicker: null,
        //editionMode: 

        initialize: function () {
            //ATTENTION!!!!!!!!!!
            //All properties which values must not be shared between instances of this object must be defined here (on the
            // initialize function).

            this.options.state = app.view_states.loading;
            this.options.onappend = (_.isFunction(this.options.onappend)) ? this.options.onappend : function () { };

            this.container = this.options.container;

            this.model = new SystemTimeConfiguration.Models.Main();

            var detectedTimezone = Core.DateTime.GetDateTimeZone();

            //this.bindEvents();

            _.bindAll(this);
        },

        append: function (container, el) {
            el = (el != null && el != undefined) ? el : this.$el;

            if (this.options.state == app.view_states.loading || this.options.state == app.view_states.shown) {
                //appending view to the main container and set state to shown

                container.append(el);

                this.options.state = app.view_states.shown;

                this.options.onappend(this);
            }

            if (this.options.state == app.view_states.hidden) {
                //append and remain hidden
                container.append(el);
            }

            if (this.options.state == app.view_states.closed) {
                //return without appending.
                return;
            }
        },
        //bindEvents: function () {
        //    //this function should be in every view that uses listenTo anywhere
        //    //all the model bindings or view-model binding should be here, to manage
        //    //the show/hide view easily
        //},
        close: function () {
            this.options.state = app.view_states.closed;

            this.remove();
            this.unbind();
        },
        //fetchTimezones: function(){
        //    callSystemTimeConfigurationService(
        //        "GET_SYSTEM_TIME_ZONES",
        //        {
        //            success: function (resp) {
        //                if ((resp != null) && (resp.Success == true) && (resp.Data != null))
        //                    templateData.timeZones = resp.Data;
        //            },
        //            async: false,
        //        }
        //    );
        //},
        hide: function () {
            this.options.state = app.view_states.hidden;

            this.$el.hide();
            this.unbind();
            this.stopListening();
        },
        preRender: function () {
            app.models.subnavbar.set('dateControl', false);
            app.models.subnavbar.set('subnavbar', false);
        },
        render: function (container, viewParams) {
            var that = this;

            if (container != null && container != undefined) this.container = container;

            if (!viewParams) viewParams = {};

            //the screens have a custompath, so it has to be specified in the customPath variable that is
            //then sent to the template loader.
            var customPath = '/app/custom-screens/IHConfiguration/system-time-configuration/';

            T.render.call(
                this,
                this.template,
                function (tmp) {
                    //start: before the view is visible, but the template was already loaded (not instanced nor appended)
                    //end:

                    //that.templateCompiler = tmp;

                    //loading the view and appeding it to the views's $el.
                    that.$el.html(tmp());


                    that.datetimePicker = new DatetimeControl.Views.Main({
                        model: new DatetimeControl.Model({
                            datetime: new Date(),
                        }),
                        autoupdate: true, 
                    });
                    that.datetimePicker.render(that.$('#datetime_picker'));
                    that.listenTo(that.datetimePicker.model, 'change', that.datepicker_model_change);

                    //appending view to the main container
                    that.append(that.options.container, that.$el);
                },
                customPath,
                'main_template'
            );
        },
        show: function () {
            this.options.state = app.view_states.shown;

            this.bindEvents();
            this.$el.show();
        },

        trigger_edited: function () {
            this.trigger('edited', this);
        },

        datepicker_model_change: function (e) {
            this.model.set(this.datetimePicker.model.toJSON());

            this.trigger_edited();
        },
        syncTimeCkx_click: function (e) {
            var target = $(e.target);

            this.model.set('syncWithInternetEnabled', target.prop('checked'));

            this.trigger_edited();
        },
        timeZoneCbx_change: function (e) {
            var target = $(e.target);

            this.model.set('timeZoneId', target.val());

            this.trigger_edited();
        },
    });

    // Required, return the module for AMD compliance.
    return SystemTimeConfiguration;

});
