"use strict";

appCore.controller("MyGoalsCtrl", ["$state", "$scope", "$http", "$timeout", "vServices", "$uibModal", "filterFilter", function ($state, $scope, $http, $timeout, vServices, filterFilter) {
    $scope.params = $state.params;
    $scope.$root.page.title = "My Goals";
    $scope.btn = {text: "My Goals"};
    $scope.today = moment().format("DD-MM-YYYY");
    $scope.goalList = [{
        hero_id:$scope.$root.gUser.id,
        lm_id:$scope.$root.gUser.emp_lm,
        goal_name:'',
        target_date: $scope.today,
        stage:'not-started',
        description:'',
        emp_first_name:$scope.$root.gUser.emp_first_name,
        emp_last_name:$scope.$root.gUser.emp_last_name,
        emp_code:$scope.$root.gUser.emp_code,
        created_date: $scope.today,
        required_minutes : 0,
        isView:false,
        image_name:[]}];
    $scope.stageOptions = [{label:'Not Started',value:'not-started'},{label:'In-Progress',value:'in-progress'},{label:'On Hold',value:'on-hold'},{label:'Completed',value:'completed'}];
    
    $scope.isModalOpen = false;
    $scope.isImageViewing = false;
    $scope.goalCommentList = [];
    $scope.goalComment = {comment:'',comment_by:$scope.$root.gUser.id};
    $scope.isConfirmModalOpen = false;
    $scope.goalToDelete={};
    $scope.templateList=[];
    $scope.goalStageCounter = [];
    $scope.currentDate = moment().format('YYYY-MM-DD');

    const init = () => {
        vServices.callApi("goal/goalStageCounter?hero_id="+$scope.$root.gUser.id, "GET", {}).then(function (counter) {
            if(counter)
                $scope.goalStageCounter = counter;
        });
        vServices.callApi("goal/heroGoalTemplate?hero_id="+$scope.$root.gUser.id, "GET", {}).then(function (tempRes) {
            if (tempRes && tempRes.length > 0) {  
                $scope.templateList = tempRes;
                tempRes.forEach((item,i)=>{
                    vServices.callApi("goal/getGoalList?hero_id="+$scope.$root.gUser.id+ '&template_id='+item.id, "GET", {}).then(function (res) {
                        if (res && res.length > 0) {                
                            // $scope.goalList = JSON.parse(JSON.stringify(res));
                            let timeCount = 0;
                            res.forEach(item=>{
                                item.isView = true;
                                item.isExpire=(item.target_date< $scope.currentDate && item.stage!='completed')?true:false;
                                timeCount += item.required_minutes;      
                                item.maxTime = Math.floor(item.required_minutes / 60)  + '.' + Math.floor(item.required_minutes % 60);             
                            });
                            item.totalMinutes = Math.floor(timeCount / 60)  + '.' + Math.floor(timeCount % 60); 
                            $scope.templateList[i]['goalList']=res;
                        }
                    });
                });
                $scope.templateList = tempRes;
                // console.log($scope.templateList);
            }


        });

    };
    init();

    // add new goal row in list
    $scope.addRow = ()=>{        
        $scope.goalList.push({
            hero_id:$scope.$root.gUser.id,
            lm_id:$scope.$root.gUser.emp_lm,
            goal_name:'',
            target_date: $scope.today,
            stage:'not-started',
            description:'',
            emp_first_name:$scope.$root.gUser.emp_first_name,
            emp_last_name:$scope.$root.gUser.emp_last_name,
            emp_code:$scope.$root.gUser.emp_code,
            created_date: $scope.today,
            required_minutes : 0,
            isView:false,
            image_name:''
        });
        // console.log('Add row');
    };

    //remove row
    $scope.removeRow = (index)=>{
        
        $scope.goalToDelete = $scope.goalList[index];
        if($scope.goalToDelete.id){
            $scope.isConfirmModalOpen = true;
        }
        else{
            $scope.goalList.splice(index,1);  
        }
    };
    $scope.cancel = ()=>{
        window.history.back();
    }

    $scope.editRow = (index,indexG) =>{
        // console.log(index,indexG);
        $scope.templateList[indexG].goalList[index].isView = false;
    }

    $scope.saveOrUpdateGoals = (index,indexG)=>{        
        // console.log($scope.templateList[indexG].goalList[index]);
        $scope.$goalList = $scope.templateList[indexG].goalList;
        $scope.$goalList.forEach(item=>{
            let img = item.image_name;
            item.image_name = {'image_name':img};
            
            if(item.image_name){
                item.image_name['sId'] = item.id;
                console.log(item);
                vServices.callApi("goal/uploadImg", "POST",item.image_name,img).then(function (res) {
                  
                });
            }
        });
        vServices.callApi("goal/saveGoalList", "POST", {data:JSON.stringify($scope.$goalList)}).then(function (res) {
            toastr.success("Your goal have been saved","Success");
            init();
        });        
    }

    $scope.opemModal = (index,indexG)=>{
        $scope.goalComment.goal_id = $scope.templateList[indexG].goalList[index].id;        
        vServices.callApi("goal/getGoalComments?goal_id="+$scope.goalComment.goal_id, "GET", {}).then(function (res) {
            $scope.goalCommentList = JSON.parse(JSON.stringify(res));
            $scope.isModalOpen = true;
        });
    }
    $scope.closeModal = ()=>{
        $scope.isModalOpen = false;
    }
    $scope.submitComment = ()=>{
        if($scope.goalComment.comment==''){
            toastr.error("Please fill all required fields.","Error");
            return false;
        }

        vServices.callApi("goal/saveGoalComments", "POST", $scope.goalComment).then(function (res) {
            toastr.success("Your comment has been saved","Success");
            $scope.isModalOpen = false;
        });
    }

    $scope.noCloseGolaDeleteModal = ()=>{
        $scope.goalToDelete = {};
        $scope.isConfirmModalOpen = false;
    }

    $scope.yesDeleteGoal = ()=>{
        
        vServices.callApi("goal/deleteGoal", "POST", {id:$scope.goalToDelete.id}).then(function (res) {
            toastr.success("Goal has been deleted","Success");
            $scope.isConfirmModalOpen = false;
            init();
        });
    }

    $scope.displayImageModal = (image)=>{
        $scope.isImageViewing = true;
        $scope.screenshotDiaplay = 'app/uploads/goals/' + image;
        console.log($scope.screenshotDiaplay);
    }
    $scope.displayImagecloseModal = ()=>{
        $scope.isImageViewing = false;
    }

}])

