"use strict";

appCore.controller("DashboardCtrl", ["$state", "$scope", "$http", "$timeout", "vServices", function ($state, $scope, $http, $timeout, vServices) {
  $scope.$root.page.title = "My Dashboard";
  $scope.pools = [];
  $scope.projectLoading = {};
  $scope.activeProject = {};
  $scope.projectDetails = [];
  $scope.tips = [];
  $scope.tipDone = [];
  $scope.isOpenTip = false;
  $scope.getAllNotfications = [];

  if (!localStorage.getItem("id_token")) {
    $state.go("login", {}, {reload: true});
  }

  $scope.closeProjectDetails = () => {$scope.projectDetails = [];};
  $scope.getProjectInfo = (o) => {
    $scope.activeProject = o;
    vServices.callApi("project/project_loading/" + o.proj_id, "GET").then(function (res) {
      if (res) {
        let temp = {};
        res.expectation.sort((a, b) => a["desg_name"] > b["desg_name"] ? 1 : a["desg_name"] < b["desg_name"] ? -1 : 0);

        for (let i = 0; i < res.expectation.length; i++) {
          let e = res.expectation[i];
          temp[e.desg_name] = {expectation: e, allocations: {}};
        }

        for (let i = 0; i < res.allocations.length; i++) {
          let e = res.allocations[i];
          temp[e.desg_name] = {expectation: temp[e.desg_name] ? temp[e.desg_name].expectation : {}, allocations: e};
        }
        $scope.projectDetails = [];
        for (let i in temp) $scope.projectDetails.push(temp [i]);
      }
    });

  };

  $scope.hideTip = () =>{
    $scope.isOpenTip = false;
  }
  
  const init = () => {

  if($scope.gUser.is_admin)  $scope.$root.menus.push({href: $scope.$root.baseurl + "/my/skills/add", type: "bg-gradient-success", name: "My Skills", hasIcon: true, icon: "fa-id-badge", iconText: "text-success", hasBadge: false, badgeType: "badge-success"});
  vServices.callApi("project/project_loading", "GET").then(function (res) {
    if (res) {
      $scope.projectLoading = res;
        setTimeout($scope.$root.callDataTable("#dashBoardProjectList"), 10000);
    }
  });
  vServices.callApi("tip/getTipForHero?heroId="+$scope.$root.gUser.id, "GET", {}).then(function (res) {
    if(res){
      $scope.tipDone = res;
    }
      vServices.callApi("tip/tip", "GET", {}).then(function (res) {
        
        if(res){
            if ($scope.tipDone.length == 0 && res[0].status == 'active'){
              $scope.tips = res[0];
              $scope.isOpenTip = true;
          }
        }
      });
  });

  // Notifications
  if($scope.$root.gUser.id != 1){
    vServices.callApi("notifications/notifyOverallAssessmentManagers?managerId="+$scope.$root.gUser.id, "GET", {}).then(function (res) {
      if(res){
        
        $scope.getAllNotfications = [
          // Overall Assessment Notifications
          {
            'count' :  res[0].count,
            'message' : res[0].n_label,
            'link' : res[0].n_url,
            'icon' : res[0].n_icon
          }
        ];
      }
    });   
    vServices.callApi("notifications/notifyGoals?managerId="+$scope.$root.gUser.id, "GET", {}).then(function (res) {
      if(res){
        
        $scope.getAllNotfications.push({
          // Goals Notifications
          'count' :  res[0].count,
          'message' : res[0].n_label,
          'link' : res[0].n_url,
          'icon' : res[0].n_icon
          });
      }
    });   
  }


  // Code for hard refresh
  if( window.localStorage )
  {
      //check if reloaded once already
      if( !localStorage.getItem('firstLoad') )
      {
          //if not reloaded once, then set firstload to true
          localStorage['firstLoad'] = true;
          //reload the webpage using reload() method
          window.location.reload();
      }
      else{
          localStorage.removeItem('firstLoad');
      }
  }
 
  };
		
  init();

  /*Time Line Start*/
  $scope.tempProjects = [];
  $scope.projectsearlier = [];
  $scope.projectsTimeline = [];
  $scope.projectsTimelineData = [];
  const getFormatDate = (d) => {
    try {
      return moment(moment(d).format('YYYY-MM-DD').toString()).toDate();
    } catch (e) {
      console.error(d);
      return new Date();
    }
  };
  const isOngoing = (o, returnType) => {
    try {
      if (returnType === 'bool')
        return moment(o.fromDate).format('DDMMYYYY').toString() === moment(o.updatedAt).format('DDMMYYYY').toString();
      else
        return moment(o.fromDate).format('DDMMYYYY').toString() === moment(o.updatedAt).format('DDMMYYYY').toString() ? moment() : o.updatedAt;
    } catch (e) {
      console.info(o.fromDate + '\t' + o.updatedAt);
      console.error(e);
      return moment();
    }
  };
  const init2 = function () {
    var data = $scope.projectsTimelineData;

    //console.log(data);
    google.charts.load("current", {packages: ["timeline"]});
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
      if (data && data.result && data.result.length > 0) {
        var container = document.getElementById('projTimelineGraph');
        var chart = new google.visualization.Timeline(container);
        var dataTable = new google.visualization.DataTable();
        dataTable.addColumn({type: 'string', id: 'Project'});
        dataTable.addColumn({type: 'string', id: 'Account'});
        dataTable.addColumn({type: 'string', id: 'style', role: 'style'});
        dataTable.addColumn({type: 'date', id: 'Start'});
        dataTable.addColumn({type: 'date', id: 'End'});

        //data.result.forEach(o => dataTable.addRows(o));
        dataTable.addRows(data.result);
        var options = {
          height: 40 * (data && data.totProject && data.totProject < 8 ? (data.totProject + 2) : 10),
          'is3D': true,
          width: container.clientWidth,
          avoidOverlappingGridLines: false,
          /*animation:{
              duration: 1000,
              easing: 'inAndOut',
              startup: true
          }*/
        };
        chart.draw(dataTable, options);

        /*$(window).resize(function() {
            chart.clearChart();
            chart.draw(dataTable, options);
        });*/
      }
    }
  };
  const checkForDateDiff = (l,o,diff)=>{
    var a = moment(l[l.length-1].updatedAt);
    var b = moment(o.updatedAt);
    var result = a.diff(b, 'days') >= diff;
    //console.log(l[l.length-1].updatedAt,o.updatedAt,result);
    return result;
  };
  const dataFormationForChart = () => {
    //console.log($scope.projectsTimeline);
    var temp = {
      dupProject: [],
      totProject: 0,
      data: [],
      result: []
    };
    temp.data = $scope.$root.sort($scope.projectsTimeline, 'fromDate', 'date', 'desc');
    temp.data = $scope.$root.sort(temp.data, 'projectid');

    $scope.projectsTimeline = [];
    temp.data.filter(o => moment(o.fromDate) < moment(o.isOngoingValue)).forEach((o, i) => {
      //console.log(moment(o.fromDate) < moment(o.isOngoingValue));
      if (temp.dupProject.indexOf(o.projectid) === -1) {
        temp.totProject++;
        temp.dupProject.push(o.projectid);
      }
      if (i > 0 && $scope.projectsTimeline[i - 1].projectid === o.projectid && moment(o.fromDate) < moment($scope.projectsTimeline[i - 1].isOngoingValue)) {
        $scope.projectsTimeline[i - 1].isOngoingValue = o.fromDate;
      }
      $scope.projectsTimeline.push(o);
    });

    $scope.projectsTimeline.forEach((o) => {
      var colorCode = o.isBillable ? (parseInt(o.partialHours) === 8 ? '#00A65A' : '#00A65A') : '#00A65A';
      temp.result.push([o.proj_name, o.acc_company_name, colorCode, getFormatDate(o.fromDate), getFormatDate(o.isOngoingValue)]);
    });
    $scope.projectsTimelineData = temp;
    init2();
  };
  const init1 = function () {
    var employeeid = parseInt($scope.$root.gUser.id);
    // console.log(employeeid);
    if (employeeid && employeeid > 1) {
      var url = "/allocation/listbyempidearlier/" + employeeid;
      vServices.callApi(url, "GET", {}).then((res) => {
        if (res) {
          //check valid partial hours
          res = res.filter(o=>o.partialHours && !Number.isNaN(o.partialHours) && parseInt(o.partialHours) > -1);
          //res = $scope.$root.sort(res, 'fromDate', 'date');
          res = $scope.$root.sort(res, 'partialHours');
          res = $scope.$root.sort(res, 'updatedAt', 'date');
          res = $scope.$root.sort(res, 'projectid', '');

          //handle one week gap between two record
          res.forEach((o,i)=>{
            if($scope.tempProjects.length > 0 && o.partialHours && $scope.tempProjects[$scope.tempProjects.length-1].projectid !== o.projectid) {
              o['ok'] = 1+'-'+i;
              $scope.tempProjects.push(o);
            }else if($scope.tempProjects.length > 0 && o.partialHours && checkForDateDiff($scope.tempProjects, o,7) && $scope.tempProjects[$scope.tempProjects.length-1].partialHours !== o.partialHours){
              o['ok'] = 2+'-'+i;
              $scope.tempProjects.push(o);
            }else if($scope.tempProjects.length > 0 && o.partialHours && !checkForDateDiff($scope.tempProjects, o,7)){
              $scope.tempProjects[$scope.tempProjects.length - 1]['ok'] = 3+'-'+i;
              $scope.tempProjects[$scope.tempProjects.length - 1].updatedAt = o.updatedAt;
            }else if($scope.tempProjects.length === 0){
              o['ok'] = 9+'-'+i;
              $scope.tempProjects.push(o);
            }
          });
          $scope.tempProjects = $scope.$root.sort($scope.tempProjects, 'fromDate', 'date');

          var dupVal = [];
          $scope.tempProjects.forEach((o, i) => {
            o['char'] = o.proj_name.substring(0, 1).toUpperCase();
            o['isOngoing'] = isOngoing(o, 'bool');
            o['isOngoingValue'] = isOngoing(o, 'value');
            if (dupVal.indexOf(o.fromDate) === -1) {
              dupVal.push(o.fromDate);
              o['new'] = true;

              $scope.projectsearlier.push(o);

              var o1 = JSON.parse(JSON.stringify(o));
              o1['new'] = false;
              $scope.projectsearlier.push(o1);
              $scope.projectsTimeline.push(o1);
            } else {
              o['new'] = false;
              $scope.projectsearlier.push(o);
              $scope.projectsTimeline.push(o);
            }
          });
          dataFormationForChart();
        }
      });
    }
  };
  init1();
  /*Time Line End*/
  
        var closeTipModal = function(){
          $("#tip-modal").modal('hide'); 	  
        }

        //add status from tip popup
        $scope.ok = (id) => {
          $scope.isOpenTip = false;
          $scope.tipreport = {
          tipID: id,
          heroID: $scope.$root.gUser.id,
          heroAction : '',
          rmsAction  : '',       
      };
            vServices.callApi("tip/addreport_ok", "POST",$scope.tipreport).then((res) => {
                  if (res && typeof res === 'string') {     
                      toastr.success(res, "Success!", {timeOut: 5000});
                      $("#tip-modal").modal('hide');
                  }
              });
        };   
        $scope.needhelp = (id) => {
          $scope.isOpenTip = false;
          $scope.tipreport = {
          tipID: id,
          heroID: $scope.$root.gUser.id,
          heroAction : '',
          rmsAction  : '',       
      };
            vServices.callApi("tip/addreport_needhelp", "POST",$scope.tipreport).then((res) => {
                  if (res && typeof res === 'string') {     
                      toastr.success(res, "Success!", {timeOut: 5000});
                      $("#tip-modal").modal('hide');
                  }
              });
        };

}]);
