/*
 * app.license.js
 * License key generator
 */

/*jslint         browser : true, continue : true,
  devel  : true, indent  : 2,    maxerr   : 50,
  newcap : true, nomen   : true, plusplus : true,
  regexp : true, sloppy  : true, vars     : false,
  white  : true
*/

/*global $, app */

app.ravLicense = (function () {
    "use strict";
    //---------------- BEGIN MODULE SCOPE VARIABLES --------------
    var stateMap = {},
        configModule,
        initModule,
        onGenerate,
        onRevoke,
        onPerpetualChanged,
        onLicenseExpiresSetOneMonth,
        onLicenseExpiresSetOneYear,
        onMaintExpiresSetOneMonth,
        onMaintExpiresSetOneYear;
    //----------------- END MODULE SCOPE VARIABLES ---------------

    //------------------- BEGIN UTILITY METHODS ------------------
    //-------------------- END UTILITY METHODS -------------------
    /*
   public class dtoRavLicense
        {
            [Required]
            public string RegisteredTo { get; set; }
            [Required]
            public Guid DbId { get; set; }
            [Required]
            public bool licenseExipres  (rental type)
            public long LicenseExpiration { get; set; }
            [Required]
            public long MaintenanceExpiration { get; set; }
            [Required]
            public List<dtoLicenseFeature> Features { get; set; }
            [Required]
            public long SiteId { get; set; }
        }
        public class dtoLicenseFeature
        {
            dtoLicenseFeature()
            {
                Count = 0;
            }
            //name of feature / product
            public string Feature { get; set; }
            //Optional count for items that require it
            public long Count { get; set; }
        }

*/

    //------------------- BEGIN EVENT HANDLERS -------------------
    onGenerate = function (event) {
        event.preventDefault();
        $.gevent.publish("app-clear-error");
        //get form data
        var formData = $("form").serializeArray({
            checkboxesAsBools: true
        });

        var submitData = app.utilB.objectifyFormDataArray(formData);
        //do features separately, above can't deal with multi select and we need to add schedtechs anyway
        let features = [];

        if ($("#perpetual").prop("checked")) {
            features.push({
                Feature: "ServiceTechs",
                Count: Number($("#techcount").val())
            });
        } else {
            if (!$("#licenseExpires").prop("checked")) {
                alert(
                    "Subscription licenses MUST have a license expiry, can not process"
                );
                return false;
            }
            features.push({
                Feature: "ActiveInternalUsers",
                Count: Number($("#subusercount").val())
            });

            features.push({
                Feature: "ActiveCustomerUsers",
                Count: Number($("#subcustcount").val())
            });
        }

        let options = $("#options").val();

        for (let i = 0; i < options.length; i++) {
            features.push({ Feature: options[i], Count: 0 });
        }

        submitData["features"] = features;
        console.log("submitData", submitData);
        //submit
        app.api.createRavLicense(submitData, function (res) {
            if (res.error) {
                $.gevent.publish("app-show-error", res.msg);
            } else {
                page(
                    "#!/ravLicenses/" +
                        stateMap.id +
                        "/" +
                        stateMap.context.params.cust_id
                );
                return false;
            }
        });

        return false; //prevent default
    };

    onRevoke = function (event) {
        event.preventDefault();
        $("#registeredTo").val("REVOKED");
        $("#licenseExpires").prop("checked", true);
        var yesterday = moment().add(-1, "days").toISOString().substring(0, 10);
        $('input[type="date"]').val(yesterday);
        $("#subcustcount").val(1);
        $("#subusercount").val(1);

        return false; //prevent default
    };

    onPerpetualChanged = function (event) {
        event.preventDefault();

        $("#perpettechcountblock").toggleClass("d-none");
        $("#subusercountblock").toggleClass("d-none");
        $("#subcustcountblock").toggleClass("d-none");

        const isPerpetual = $("#perpetual").prop("checked");
        $("#licenseExpires").prop("checked", !isPerpetual);
        $("#title").text(
            isPerpetual ? "Perpetual license" : "Subscription license"
        );

        return false; //prevent default
    };

    onLicenseExpiresSetOneMonth = function (event) {
        event.preventDefault();
        $("#licenseExpirationDate").val(
            moment().add(1, "months").toISOString().substring(0, 10)
        );

        return false; //prevent default
    };

    onLicenseExpiresSetOneYear = function (event) {
        event.preventDefault();
        $("#licenseExpirationDate").val(
            moment().add(1, "years").toISOString().substring(0, 10)
        );

        return false; //prevent default
    };

    onMaintExpiresSetOneMonth = function (event) {
        event.preventDefault();
        $("#maintenanceExpirationDate").val(
            moment().add(1, "months").toISOString().substring(0, 10)
        );

        return false; //prevent default
    };

    onMaintExpiresSetOneYear = function (event) {
        event.preventDefault();
        $("#maintenanceExpirationDate").val(
            moment().add(1, "years").toISOString().substring(0, 10)
        );

        return false; //prevent default
    };

    // onSelectAllAddOns = function (event) {
    //     event.preventDefault();
    //     $('#wbi').prop('checked', true);
    //     $('#mbi').prop('checked', true);
    //     $('#ri').prop('checked', true);
    //     $('#qbi').prop('checked', true);
    //     $('#qboi').prop('checked', true);
    //     $('#pti').prop('checked', true);
    //     $('#quickNotification').prop('checked', true);
    //     $('#exportToXls').prop('checked', true);
    //     $('#outlookSchedule').prop('checked', true);
    //     $('#oli').prop('checked', true);
    //     $('#importExportCSVDuplicate').prop('checked', true);

    //     return false; //prevent default
    // };

    // onTemplates = function(event) {
    //     event.preventDefault();
    //     alert("STUB: templates");

    //     return false; //prevent default
    // };

    //-------------------- END EVENT HANDLERS --------------------

    //------------------- BEGIN PUBLIC METHODS -------------------
    //CONFIGMODULE
    //
    configModule = function (context) {
        stateMap.context = context.context;
        if (stateMap.context.params.id) {
            stateMap.id = stateMap.context.params.id;
        }
    };

    //INITMODULE
    //
    initModule = function ($container) {
        if (typeof $container === "undefined") {
            $container = $("#app-shell-main-content");
        }
        $container.html(Handlebars.templates["app.ravLicense"]({}));

        ///ravLicense/:id
        //id is always site id and this form is only to make a new license, not to view one

        //case 3233 customer list
        //Fill customer list combo
        // var customerList = {};

        //get company name to pre-fill regto
        //api/site/77/name

        app.api.get("site/" + stateMap.id + "/newlicenseinfo", function (res) {
            if (res.error) {
                $.gevent.publish("app-show-error", res.msg);
            } else {
                $("#registeredTo").val(res.name);
                $("#dbId").val(res.dbid);
            }
        });

        //Context menu
        app.nav.contextClear();

        ////app.nav.setContextTitle("License");

        //make context menu

        //Context menu
        app.nav.contextClear();
        app.nav.contextAddButton(
            "btn-generate",
            "Generate and Send",
            "key",
            onGenerate
        );

        // app.nav.contextAddButton('btn-select-all-addons', 'All', 'check-all', onSelectAllAddOns);
        // app.nav.contextAddLink("licenseRequests/", "Requests", "voice");
        // app.nav.contextAddLink("licenseTemplates/", "", "layers");
        //case 3233

        app.nav.contextAddLink(
            "ravLicenses/" +
                stateMap.id +
                "/" +
                stateMap.context.params.cust_id,
            "Licenses",
            "ticket"
        ); //from here to new license

        app.nav.contextAddButton("btn-revoke", "Revoke", "nuke", onRevoke);

        //set all date inputs to today plus one year
        var oneYearFromNow = moment()
            .add(1, "years")
            .toISOString()
            .substring(0, 10);
        $('input[type="date"]').val(oneYearFromNow);
        $("#siteId").val(stateMap.id);

        //var oneMonthFromNow = moment().add(1, 'months').toISOString().substring(0, 10);
        //$('#lockoutDate').val(oneMonthFromNow);
        // bind actions
        $("#btn-revoke").bind("click", onRevoke);
        $("#perpetual").bind("change", onPerpetualChanged);

        $("#btn-license-expires-plus-one-month").bind(
            "click",
            onLicenseExpiresSetOneMonth
        );
        $("#btn-license-expires-plus-one-year").bind(
            "click",
            onLicenseExpiresSetOneYear
        );

        $("#btn-maint-expires-plus-one-month").bind(
            "click",
            onMaintExpiresSetOneMonth
        );
        $("#btn-maint-expires-plus-one-year").bind(
            "click",
            onMaintExpiresSetOneYear
        );
    };

    // return public methods
    return {
        configModule: configModule,
        initModule: initModule
    };
    //------------------- END PUBLIC METHODS ---------------------
})();
