"use strict";
appCore.controller("NewsLetterAddCtrl", ["$state", "$scope", "$http", "$timeout", "vServices", function ($state, $scope, $http, $timeout, vServices) {
    $scope.param = $state.params;
    $scope.createButton = {
        heading: "Add News Letter",
        text: "Add News Letter",
        icon: "fa-add"
    };
    $scope.$root.page.title = "Add News Letter";
    $scope.newsLetters = [];
    $scope.countryList = [];
    $scope.getCon=[];

    $scope.save = () => {
        $scope.newsLetters['cty_location'] = $scope.getCon;

			vServices.callApi("newsletter/addNewsLetter", "POST", $scope.newsLetters).then((res) => {
            if (res) {
                toastr.success(res, "Success!", {timeOut: 5000});
                $scope.$root.updateMenu();
                $state.go("newsLetterList", {}, {reload: true});
            }
        });
    };
    $scope.toggleOne = (val) =>{
        var temArr = [];
        $scope.countryList.forEach(i=>{
            if(i.val){
                temArr.push(i.id);
            }
            if(!i.val){
                const index = temArr.indexOf(val);
                if (index > -1) { // only splice array when item is found
                    temArr.splice(index, 1); // 2nd parameter means remove one item only
                }
            }
        })
        $scope.getCon = ','+temArr.join(",")+',';     
    }
    const init = function () {
        vServices.callApi("commonfunc/getCountriesList", "GET", {}).then(function (res) {
            if (res && res.length > 0) 
            res.forEach(i=>{
                i.val = false;
            })
            $scope.countryList = res;
            console.log($scope.countryList);
          });
        vServices.callApi("commonfunc/getCountriesList", "GET", {}).then(function (res) {
            if (res && res.length > 0) 
            $scope.countryList = res;
        });

        if ($scope.param && typeof $scope.param.emailtemplateid !== "undefined") {
            vServices.callApi("newsletter/emailTemplate/" + $scope.param.emailtemplateid, "GET", {}).then((obj) => {
                if (obj) {
                    $scope.newsLetters = obj;
                }
            });
        }
    };
    init();
}]);
