system.controller("OptionFilterLinkController", OptionFilterLinkController);

function OptionFilterLinkController($scope, $http, $rootScope, $interval, $window, Upload, $q) {
    this.__proto__ = new BaseController($scope, $http, $rootScope, Upload)

    const CREATE = 'create';
    const EDIT = 'edit';

    $scope.props = {
        type: 'option_filter_link'
    };
    $scope.states = {
        loading: true,
        modalMode: CREATE
    }
    $scope.categories = [];
    $scope.links = [];
    $scope.activeLink = null;

    $scope.openEditForm = function(link)
    {
        if (link) {
            $scope.states.modalMode = EDIT;
            $scope.activeLink = angular.copy(link);
        } else {
            $scope.states.modalMode = CREATE;
            $scope.activeLink = {
                title: '',
                keyword: '',
                url: '',
                target_id: ''
            };
        }

        if ($scope.activeLink.target_id) {
            $scope.activeLink.target_id = $scope.activeLink.target_id.toString();
        }

        $('#modalOptionLink').modal({
            modal: true,
            persist: true,
            // position: [30, 0],
            autoPosition: true
        });
    }

    $scope.getCategory = function(id) {
        return $scope.categories.find(function(category) {
            return category.id === parseInt(id);
        });
    }

    $scope.save = function() {
        saveLink($scope.activeLink)
    }

    $scope.importFile = function(files)
    {
        let locale = '';
        if (typeof localePrefix !== 'undefined' && localePrefix !== '') {
            locale = '/' + localePrefix;
        }

        if (files && files[0]) {

            let file = files[0];
            if (['csv', 'xls', 'xlsx'].includes(file.name.split('.').pop())) {

                $scope.states.loading = true;
                const formData = new FormData();
                formData.append("file", file);

                const request = new XMLHttpRequest();
                request.open("POST", locale + '/seo/import-option-link');
                request.onload = function (e) {

                    const res = JSON.parse(this.responseText);
                    if(res.status === 'successful') {
                        toastr.success('Imported!');
                        fetchLinks().then(function(res) {
                            if (typeof res != 'undefined' && res.data.status === 'successful') {
                                $scope.links = res.data.result;
                            }
                        });
                    } else {
                        toastr.error('Something went wrong please try again!');
                    }

                    $scope.$applyAsync(function () {
                        $scope.states.loading = false;
                    });

                };
                request.send(formData);

            } else {
                toastr.warning('Extention of file invalid!');
            }

        }
    }

    $scope.deleteLink = function (link) {
        const param = {
            title: 'Delete Item',
            customText: 'Confirm to delete this item!',
            confirmButtonText: 'Ok',
            cancelButtonText: 'No',
            arg: {id: link.id}
        };

        $scope.callConfirmModal(param, function (arg) {
            $http({
                method: 'delete',
                url: base_api_url + '/option_link/' + arg.id,
            }).then(function success(response) {
                if (response.data.status === 'successful') {
                    toastr.success('Deleted!');
                    fetchLinks().then(function(res) {
                        if (typeof res != 'undefined' && res.data.status === 'successful') {
                            $scope.links = res.data.result;
                        }
                    });
                } else {
                    toastr.error('Error delete keywordLink!');
                }
            });
        });
    }

    async function init() {

        Promise.all([getProductCategories(), fetchLinks()]).then(resp => {

            if (typeof resp[0] != 'undefined' && resp[0].data.status === 'successful') {
                $scope.categories = resp[0].data.result
            }

            if (typeof resp[1] != 'undefined' && resp[1].data.status === 'successful') {
                $scope.links = resp[1].data.result;
            }

            $scope.states.loading = false;

            safeApply();
        });
    }

    function getProductCategories () {
        return $http.get(base_api_url + '/categories');
    }

    function fetchLinks () {
        let filters = new URLSearchParams({
            'sorts': '-id',
            'filters': 'type=' + $scope.props.type
        });
        return $http.get(base_api_url + '/option_link?' + filters.toString());
    }

    function buildLinkData(data, id)
    {
        let link = {
            'title': data.title,
            'keyword': data.keyword,
            'url': data.url,
            'type': $scope.props.type,
            'target_id': data.target_id,
        }

        if (id) {
            link.id = id;
        }

        if (!link.url || !link.keyword || !link.target_id) {
            toastr.error("Error, Invalid input data!");
            return null;
        }

        return link
    }

    function saveLink (data) {
        let id = null;
        if ($scope.states.modalMode === EDIT && data.id) {
            id = data.id;
        }

        if (id) {
            return updateLink(data, id);
        } else {
            return createLink(data);
        }
    }

    function createLink(data)
    {
        let link = buildLinkData(data);
        if (link) {
            $scope.loaddingButton('#btnSaveLink', 'Saving . . .');
            $http({
                method: 'post',
                url: base_api_url + '/option_link',
                data: link
            }).then(function success(response) {
                $scope.stopLoaddingButton('#btnSaveLink');

                if (response.data.status === 'successful') {

                    $('#modalOptionLink').modal('hide');
                    fetchLinks().then(function(res) {
                        if (typeof res != 'undefined' && res.data.status === 'successful') {
                            $scope.links = res.data.result;
                        }
                    });

                    /*@todo*/

                    safeApply();

                } else {
                    toastr.error('Error store Link!');
                }
            });
        }

    }

    function updateLink(data, id)
    {
        let link = buildLinkData(data, id);
        if (link) {
            $scope.loaddingButton('#btnSaveLink', 'Saving . . .');
            $http({
                method: 'put',
                url: base_api_url + '/option_link/' + id,
                data: link
            }).then(function success(response) {
                $scope.stopLoaddingButton('#btnSaveLink');

                if (response.data.status === 'successful') {

                    $('#modalOptionLink').modal('hide');
                    fetchLinks().then(function(res) {
                        if (typeof res != 'undefined' && res.data.status === 'successful') {
                            $scope.links = res.data.result;
                        }
                    });

                    /*@todo*/

                    safeApply();

                } else {
                    toastr.error('Error update Link!');
                }
            });
        }
    }

    function safeApply() {
        if ($scope.$root.$$phase !== '$apply' && $scope.$root.$$phase !== '$digest') {
            $scope.$apply();
        }
    }

    init().then(r => {});
}