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

function TagConfigController($rootScope, $scope, $http, Upload) {
    $scope.filters = {};
    $scope.items = [];
    $scope.ajaxFindRequest = null;
    $scope.titleModal = "Create tag config";
    $scope.pagesCount = 0;
    $scope.tags = [];
    $scope.allCategories = [];
    $scope.uploading = false;

    this.initialize = function () {
        $scope.getCategories();
        $scope.getTags();
        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.post("/seo/tag/config/find", 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.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;
        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.find();
    };

    initalFilters = function () {
        $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 = (tagConfig, title = "Edit tag config") => {
        $scope.tagConfig = angular.copy(tagConfig);
        if (tagConfig.type == "CATEGORY") {
            $scope.tagConfig.refer = $scope.getByField($scope.allCategories, "id", tagConfig.refer_id);
        } else {
            $scope.tagConfig.refer = $scope.getByField($scope.tags, "id", tagConfig.refer_id);
        }
        if (tagConfig.related_type == "CATEGORY") {
            $scope.tagConfig.related = $scope.getByField($scope.allCategories, "id", tagConfig.related_id);
        } else {
            $scope.tagConfig.related = $scope.getByField($scope.tags, "id", tagConfig.related_id);
        }
        $scope.tagConfig.start_at = new Date($scope.tagConfig.start_at);
        $scope.titleModal = title;
        $("#modalTagConfig").modal();
    };

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

    $scope.create = () => {
        let tagConfig = {};
        tagConfig.start_at = new Date();
        tagConfig.type = "-1";
        tagConfig.related_type = "-1";
        $scope.titleModal = "Create tag config";
        $scope.openModal(tagConfig, "Create tag config");
    };

    $scope.buildUrl = function (url) {
        url = base_api_url + url;
        return url;
    };

    $scope.getCategories = function () {
        var url = $scope.buildUrl("/category?page_size=-1");
        $http.get(url).then((response) => {
            if (response.data.status == "successful") {
                $scope.allCategories = response.data.result;
            }
        });
    };

    $scope.getTags = function () {
        $http.get($scope.buildUrl("/tag?fields=id,title,slug&page_size=-1")).then(
            function success(response) {
                if (response.data.status == "successful") {
                    $scope.tags = response.data.result;
                } else {
                    $scope.tags = [];
                }
            },
            function error(response) {}
        );
    };

    $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/tag/config/save", data).then(function (response) {
                $scope.ajaxFindRequest = null;
                $scope.isSaving = false;
                $scope.isShowHideLoading(false);

                if (response.data.status === "successful") {
                    $scope.find();
                    $("#modalTagConfig").modal("hide");
                    toastr.success("Tag config saved successfully");
                }
            });
        }
    };

    $scope.buildData = () => {
        let result = {};
        if ($scope.tagConfig.id) {
            result.id = $scope.tagConfig.id;
        }
        if ($scope.tagConfig.type) {
            result.type = $scope.tagConfig.type;
        }
        if ($scope.tagConfig.refer) {
            result.refer_id = $scope.tagConfig.refer.id;
            if ($scope.tagConfig.type == "CATEGORY") {
                result.refer_name = $scope.tagConfig.refer.name;
            } else {
                result.refer_name = $scope.tagConfig.refer.title;
            }
            result.refer_url = $scope.tagConfig.refer.slug;
        }
        if ($scope.tagConfig.related_type) {
            result.related_type = $scope.tagConfig.related_type;
        }
        if ($scope.tagConfig.related) {
            result.related_id = $scope.tagConfig.related.id;
        }
        if ($scope.tagConfig.related_name) {
            result.related_name = $scope.tagConfig.related_name;
        }
        if ($scope.tagConfig.related_url) {
            result.related_url = $scope.tagConfig.related_url;
        }
        if ($scope.tagConfig.image_url) {
            result.image_url = $scope.tagConfig.image_url;
        }
        return result;
    };

    $scope.validate = () => {
        let retval = false;
        if ($scope.tagConfig.type == "-1") {
            toastr.error("Please select type!");
            retval = true;
        }
        if (typeof $scope.tagConfig.refer === "undefined" || $scope.tagConfig.refer == "") {
            toastr.error("Please select refer!");
            retval = true;
        }
        if ($scope.tagConfig.related_type == "-1") {
            toastr.error("Please select related type!");
            retval = true;
        }
        if (typeof $scope.tagConfig.related === "undefined" || $scope.tagConfig.related == "") {
            toastr.error("Please select related!");
            retval = true;
        }
        if (typeof $scope.tagConfig.related_name === "undefined" || $scope.tagConfig.related_name == "" || $scope.tagConfig.related_name == null) {
            toastr.error("Please enter related name!");
            retval = true;
        }
        if (typeof $scope.tagConfig.related_url === "undefined" || $scope.tagConfig.related_url == "" || $scope.tagConfig.related_url == null) {
            toastr.error("Please enter related url!");
            retval = true;
        }
        if (typeof $scope.tagConfig.image_url === "undefined" || $scope.tagConfig.image_url == "") {
            toastr.error("Please upload image!");
            retval = true;
        }
        return retval;
    };

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

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

    $scope.getByField = function (list, fieldName, value) {
        var retVal = null;
        list.forEach(function (item) {
            if (item[fieldName] == value) {
                retVal = item;
            }
        });
        return retVal;
    };

    $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;
    };

    $scope.changeRelated = function () {
        if ($scope.tagConfig.related_type == "TAG") {
            $scope.tagConfig.related_name = $scope.tagConfig.related.title;
            $scope.tagConfig.related_url = $scope.tagConfig.related.slug;
        } else {
            $scope.tagConfig.related_name = $scope.tagConfig.related.name;
            $scope.tagConfig.related_url = $scope.tagConfig.related.slug;
        }
    };

    $scope.changeRelatedType = () => {
        $scope.tagConfig.related = {};
        $scope.tagConfig.related_name = "";
    };

    $scope.uploadImages = async function (files) {
        let supportedFilesType = ["image/png", "image/jpg", "image/jpeg", "image/gif"];
        let supportedFilesExtentions = ["jpg", "png"];

        if (files) {
            try {
                let imagesUploaded = [];
                let imageFile = null;
                if (files && files.length) {
                    imageFile = files[0];

                    let fileExtention = imageFile.name.split(".").pop();
                    if (supportedFilesExtentions.includes(fileExtention) && supportedFilesType.includes(imageFile.type)) {
                        $scope.uploading = true;
                        imagesUploaded = await $scope.uploads(files);

                        loadMime(imageFile, function (_type) {
                            if (_type == "unknown") {
                                $scope.$apply(function () {
                                    $scope.uploading = false;
                                });
                                toastr.warning("Error image format not supported! (supported: jpg, png)");
                            }
                        });
                    } else {
                        toastr.warning("Error image format not supported! (supported: jpg, png)");
                    }
                }

                if (imagesUploaded.length) {
                    $scope.$applyAsync(function () {
                        $scope.tagConfig.image_url = imagesUploaded.pop();
                        $scope.uploading = false;
                    });
                }
            } catch (error) {
                console.log(error);
                toastr.error("Error upload images!");
            }
        }
    };

    function loadMime(file, callback) {
        //List of known mimes
        var mimes = [
            {
                mime: "image/jpeg",
                pattern: [0xff, 0xd8, 0xff],
                mask: [0xff, 0xff, 0xff],
            },
            {
                mime: "image/png",
                pattern: [0x89, 0x50, 0x4e, 0x47],
                mask: [0xff, 0xff, 0xff, 0xff],
            },
            // you can expand this list @see https://mimesniff.spec.whatwg.org/#matching-an-image-type-pattern
        ];

        function check(bytes, mime) {
            for (var i = 0, l = mime.mask.length; i < l; ++i) {
                if ((bytes[i] & mime.mask[i]) - mime.pattern[i] !== 0) {
                    return false;
                }
            }
            return true;
        }

        var blob = file.slice(0, 4); //read the first 4 bytes of the file

        var reader = new FileReader();
        reader.onloadend = function (e) {
            if (e.target.readyState === FileReader.DONE) {
                var bytes = new Uint8Array(e.target.result);

                for (var i = 0, l = mimes.length; i < l; ++i) {
                    if (check(bytes, mimes[i])) return callback(mimes[i].mime);
                }

                return callback("unknown");
            }
        };
        reader.readAsArrayBuffer(blob);
    }

    $scope.uploads = function (files, type = "default") {
        return new Promise(function (resolve, reject) {
            Upload.upload({
                url: baseFileManagerUrl + "/upload",
                data: { upload: files, type: type },
            }).then(
                function (resp) {
                    if (resp.data.status == "successful") {
                        let upload = resp.data.upload;
                        resolve(upload);
                    } else {
                        reject(0);
                    }
                },
                function (resp) {
                    reject(0);
                },
                function (evt) {
                    let progressPercentage = parseInt((100.0 * evt.loaded) / evt.total);
                    $scope.progressPercentage = progressPercentage;
                }
            );
        });
    };

    this.initialize();
}
