/*global angular*/
(function () {
    angular
        .module('simplAdmin.core')
        .controller('DistrictListCtrl', ['districtService', 'stateProvinceService', 'countryService', 'translateService', '$stateParams', DistrictListCtrl]);

    function DistrictListCtrl(districtService, stateProvinceService, countryService, translateService, $stateParams) {
        var vm = this;
        vm.tableStateRef = {};

        vm.countries = [];
        vm.stateOrProvinces = [];
        vm.districts = [];
        vm.stateOrProvinceId = $stateParams.stateOrProvinceId;
        vm.translate = translateService;

        vm.onCountrySelected = function () {
            vm.getStateOrProvinces();
        };

        vm.getStateOrProvinces = function () {
            stateProvinceService.getAllStateOrProvinces(vm.countryId).then(function (result) {
                vm.stateOrProvinces = result.data;
            });
        };

        vm.onStateOrProvinceSelected = function () {
            vm.getDistricts(vm.tableStateRef);
        };

        vm.getDistricts = function (tableState) {
            vm.tableStateRef = tableState;
            vm.isLoading = true;
            districtService.getDistricts(vm.stateOrProvinceId, tableState).then(function (result) {
                vm.districts = result.data.items;
                tableState.pagination.numberOfPages = result.data.numberOfPages;
                tableState.pagination.totalItemCount = result.data.totalRecord;
                vm.isLoading = false;
            });
        };

        vm.deleteDistrict = function deleteDistrict(district) {
            bootbox.confirm('Are you sure you want to delete this state or province: ' + simplUtil.escapeHtml(district.name), function (result) {
                if (result) {
                    districtService.deleteDistrict(district)
                        .then(function (result) {
                            vm.getDistricts(vm.tableStateRef);
                            toastr.success(district.name + ' has been deleted');
                        })
                        .catch(function (response) {
                            toastr.error(response.data.error);
                        });
                }
            });
        };

        function init() {
            countryService.getAllCountries().then(function (result) {
                vm.countries = result.data;
                vm.countryId = 0;
            });
        }

        init();
    }
})();
