system.controller("RedirectController", RedirectController);
system.config(function ($mdDateLocaleProvider) {
    $mdDateLocaleProvider.formatDate = function (date) {
        return moment(date).format("DD/MM/YYYY");
    };
});

function RedirectController($rootScope, $scope, $http, Upload, $window) {
    $scope.filters = {};
    // Set adgroup status by statues
    $scope.statuses = [
        { code: "", name: "All" },
        { code: "PENDING", name: "Pending" },
        { code: "ACTIVE", name: "Active" },
    ];
    $scope.pageSizes = [
        { code: "50", name: "50 items" },
        { code: "100", name: "100 items" },
        { code: "200", name: "200 items" },
        { code: "500", name: "500 items" },
    ];
    $scope.items = [];
    $scope.ajaxFindRequest = null;
    $scope.titleModal = "Add redirect";
    $scope.pagesCount = 0;
    $scope.excelFile = null;
    
    $scope.locales = {};
    $scope.currentLocale = (CURRENT_LOCALE != '') ? CURRENT_LOCALE : 'us';

    this.initialize = function () {
        if (localesList) {
            for (var key in localesList) {
                if (localesList[key].text !== "Central") {
                    $scope.locales[key] = '';
                }
            }
        }

        initalFilters();
        resetFilter();
    };

    $scope.reset = function () {
        $scope.isSaving = false;
        $scope.isFinding = false;
        resetFilter();
    };

    $scope.keypressFilter = function (event) {
        if (event.keyCode === 13) {
            $scope.find(true);
        }
    };
    $scope.getByCode = function (list, code) {
        var retVal = null;
        list.forEach(function (item) {
            if (item.code == code) {
                retVal = item;
            }
        });
        //return
        return retVal;
    };

    $scope.changeSelected = function () {
        if ($scope.filters.status.code != "") {
            $scope.filters.not_advertising = 0;
        }
    };

    $scope.find = function (isChangePageData) {
        if ($scope.ajaxFindRequest === null) {
            if (isChangePageData) {
                $scope.filters.page_id = 0;
            }
            $scope.isShowHideLoading(true);
            $scope.ajaxFindRequest = $http.get("/seo/redirect/find", { params: buildFilter() }).then(function (response) {
                $scope.ajaxFindRequest = null;
                $scope.isSaving = false;

                if (response.data.status === "successful") {
                    $scope.items = response.data.items;
                    $scope.isShowHideLoading(false);
                    $scope.pagesCount = response.data.pagesCount;
                }
            });
        }
    };

    $scope.handleUpload = function (excelFile) {
        if (excelFile) {
            var locales = Object.keys($scope.locales)
            if (locales.length != 0) { // localizations
                locales.forEach(function (locale) {
                    const url = $window.location.origin + `/${locale}/seo/redirect/import?ignore_localization=1`;
                    uploadFile(url, excelFile, locale);
                });
            } else {
                const url = '/seo/redirect/import';
                uploadFile(url, excelFile, $scope.currentLocale);
            }
        }
    }

    function uploadFile(url, excelFile, locale) {
        Upload.upload({
            url: url,
            data: {file: excelFile}
        }).then(function (response) {
            toastr.success(`Import thành công ${response.data.affectedRow} bản ghi cho thị trường ${locale.toUpperCase()}.`);
            $scope.find(true);
        }, function (error) {
            toastr.error('ERROR. Please try again');
        });
    }

    $scope.export = function () {
        var params = buildFilter();
        delete params.page_id;
        params.response = 'excel';
        var exportUrl = '/seo/redirect/find?' + $.param(params);
        if (CURRENT_LOCALE && CURRENT_LOCALE != '') {
            exportUrl = '/' + CURRENT_LOCALE + exportUrl;
        }
        window.open(exportUrl, '_blank');
    }

    $scope.isShowHideLoading = function (val) {
        $scope.isShowLoading = val;
    };

    buildFilter = function () {
        var retVal = {};
        if ($scope.filters.keyword != "") {
            retVal.keyword = $scope.filters.keyword;
        }
        if (typeof $scope.filters.status != "undefined" && typeof $scope.filters.status.code != "undefined" && $scope.filters.status.code != "") {
            retVal.status = $scope.filters.status.code;
        }
        retVal.page_id = $scope.filters.page_id;
        if (typeof $scope.filters.page_size != "undefined" && typeof $scope.filters.page_size.code != "undefined" && $scope.filters.page_size.code != "") {
            retVal.page_size = $scope.filters.page_size.code;
        }
        return retVal;
    };

    getParams = function (filter) {
        var params = [];
        for (var key in filter) {
            var filterValue = filter[key];
            var param = "";
            if (typeof filterValue == "object" || typeof filterValue == "array") {
                if (filterValue.length > 0) {
                    param = key + "=" + filterValue.join(",");
                }
            } else {
                param = key + "=" + filterValue;
            }
            if (param != "") {
                params.push(param);
            }
        }
        return params;
    };

    resetFilter = function () {
        $scope.filters.page_id = 0;
        $scope.filters.keyword = "";
        $scope.filters.status = { code: "", name: "---NaN---" };

        $scope.find();
    };

    initalFilters = function () {
        $scope.filters.status = $scope.statuses[0];
        $scope.filters.page_size = $scope.pageSizes[0]
        $scope.filters.keyword = "";
    };

    $scope.summarizeDateTime = function (dateTime, withYear) {
        if (dateTime != null) {
            var outputFormat = "$3/$2";
            if (withYear) {
                outputFormat += "/$1";
            }
            outputFormat += " $4:$5";
            return dateTime.replace(/(\d{4})-(\d{2})-(\d{2})\s+(\d{1,2}):(\d{1,2}):.*/, outputFormat);
        }
    };

    $scope.openModal = (redirect) => {
        $scope.redirect = angular.copy(redirect);
        $scope.redirect.start_at = new Date($scope.redirect.start_at);
        $scope.titleModal = "Edit redirect";
        $("#modalRedirect").modal();
    };

    $scope.closeModal = () => {
        $("#modalRedirect").modal("hide");
    };

    $scope.create = () => {
        let redirect = {};
        redirect.start_at = new Date();
        redirect.status = "ACTIVE";
        $scope.titleModal = "Add new redirect";
        $scope.openModal(redirect);
    };

    $scope.save = () => {
        if ($scope.ajaxFindRequest === null) {
            $scope.isShowHideLoading(true);
            let validate = $scope.validate();
            if (validate) {
                $scope.ajaxFindRequest = null;
                $scope.isSaving = false;
                $scope.isShowHideLoading(false);
                return;
            }
            let data = $scope.buildData();
            $scope.ajaxFindRequest = $http.post("/seo/redirect/save", data).then(function (response) {
                $scope.ajaxFindRequest = null;
                $scope.isSaving = false;
                $scope.isShowHideLoading(false);

                if (response.data.status === "successful") {
                    $scope.find();
                    $("#modalRedirect").modal("hide");
                }
            });
        }
    };

    $scope.buildData = () => {
        let result = {};
        if ($scope.redirect.id) {
            result.id = $scope.redirect.id;
        }
        if ($scope.redirect.url) {
            result.url = $scope.redirect.url;
        }
        if ($scope.redirect.link_redirect) {
            result.link_redirect = $scope.redirect.link_redirect;
        }
        if ($scope.redirect.start_at) {
            result.start_at = formatDate($scope.redirect.start_at, 'dd/mm/yyyy');
        }
        if ($scope.redirect.status) {
            result.status = $scope.redirect.status;
        }
        return result;
    };

    $scope.validate = () => {
        let retval = false;
        if (typeof $scope.redirect.url === "undefined" || $scope.redirect.url == "") {
            toastr.error("Please enter url");
            retval = true;
        }
        if (typeof $scope.redirect.link_redirect === "undefined" || $scope.redirect.link_redirect == "") {
            toastr.error("Please enter link redirect");
            retval = true;
        }
        if (typeof $scope.redirect.start_at === "undefined" || $scope.redirect.start_at == "") {
            toastr.error("Please enter start time");
            retval = true;
        }
        if (typeof $scope.redirect.status === "undefined" || $scope.redirect.status == "") {
            toastr.error("Please enter status");
            retval = true;
        }
        return retval;
    };

    $scope.delete = (redirect) => {
        if (confirm("Are you sure delete url: '" + redirect.url + "' ?")) {
            $scope.isShowHideLoading(true);
            $scope.ajaxFindRequest = $http.post("/seo/redirect/delete", { id: redirect.id }).then(function (response) {
                $scope.ajaxFindRequest = null;
                $scope.isShowHideLoading(false);

                if (response.data.status === "successful") {
                    $scope.find();
                }
            });
        }
    };

    $scope.myFunct = function (keyEvent) {
        if (keyEvent.which === 13) $scope.find();
    };

    formatDate = function (date, formatString) {
        if (typeof date == "string") {
            var dateStr = date.replace(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/, "$2/$1/$3");
            date = new Date(dateStr);
        }
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var ampm = hours >= 12 ? "pm" : "am";
        hours = hours % 12;
        hours = hours ? hours : 12; // the hour '0' should be '12'
        minutes = minutes < 10 ? "0" + minutes : minutes;
        var strTime = hours + ":" + minutes + " " + ampm;
        if (formatString == "dd/mm/yyyy") {
            return date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
        }
        return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear() + "  " + strTime;
    };

    this.initialize();
}
