"use strict";
appCore.controller("MyDiaryUnfilledReportCtrl1", ["$state", "$scope", "$http", "$timeout", "vServices", "$uibModal", "$document",
  function ($state, $scope, $http, $timeout, vServices, $uibModal, $document) {
    $scope.$root.page.title = "My Diary Unfilled Report";
    $scope.project = [];
    $scope.selectAll = {selected: false};
    $scope.CheckedId = "";
    $scope.tblheader = [];
    $scope.showLockDiv = false;
    $scope.myDiary = {default: [], project: [], heroes: [], datatable: []};
    $scope.tooltip = () => {
      $(document).find(".customTooltip:not([data-val=0])").tooltipster({
        theme: "tooltipster-punk",
        content: "Loading...",
        trigger: "hover",
        contentAsHTML: true,
        // 'instance' is basically the tooltip. More details in the "Object-oriented Tooltipster" section.
        functionBefore: function (instance, helper) {

          var $origin = $(helper.origin);
          //console.log("call api " + ($origin.data("loaded") !== true));
          // we set a variable so the data is only loaded once via Ajax, not every time the tooltip opens
          if ($origin.data("loaded") !== true) {
            //console.log("call api");
            var date = $origin.attr("data-date");
            var id = $origin.attr("data-id");
            vServices.callApi("mydiary/unfilled_detail?date=" + date + "&emp_id=" + id, "GET", {}).then((res) => {
              //   convertDataForMyDiary(res)
              var data = "";
              if (res) {
                data = "<table><tr><th>Project</th><th>Hours Logged</th></tr>";
                res.forEach((o) => {data += o.logged_hours ? "<tr><td>" + o.proj_name + "</td><td>" + o.logged_hours + "</td></tr>" : "";});
                data += "</table>";
              }
              //console.log(data);
              // call the 'content' method to update the content of our tooltip with the returned data.
              // note: this content update will trigger an update animation (see the updateAnimation option)
              instance.content(data);

              // to remember that the data has been loaded
              $origin.data("loaded", true);
            });
            //$.get('http://example.com/ajax.php', function(data) {

            //   });
          }
        }
      });
    };
    $scope.filter = {
      fromDate: moment().subtract(2, "days").format("DD-MM-YYYY"),
      toDate: moment().format("DD-MM-YYYY"),
      minHours: 0,
      project: 0,
      pageName: "My Diary Report",
      selType: "Default",
      type: [{val: "View Type"}, {val: "Default"}, {val: "Project",}, {val: "Hero",}]
    };
    $scope.myDiaryLock = {
      LockTillDate: moment().format("DD-MM-YYYY")
    };
    $scope.$watch("filter.selType", (newValue, oldValue) => {
      $scope.filter.pageName = "My Diary Unfilled Report of " + newValue + " View";
      $scope.$root.page.title = "My Diary Unfilled Report of " + newValue + " View " + $scope.filter.fromDate + " - " + $scope.filter.toDate;
    });
    let numOr0 = n => isNaN(n) ? 0 : n;

    $scope.totalHoursNew = (a, k, d) => d && d.length > 0 ? d.map(o => o[k]).reduce((a, b) => parseFloat(numOr0(a)) + parseFloat(numOr0(b))) : null;
    $scope.totalHours = (a, k, d) => d.map(o => o[k]).reduce((a, b) => parseFloat(numOr0(a)) + parseFloat(numOr0(b)));
    $scope.condition = (i, d, data, c) => i === 0 ? true : (i > 0 && parseInt(d[c]) !== parseInt($scope.myDiary[data][i - 1][c]));

    const convertDataForProject = res => {
      if (res) {
        $scope.project = [];
        $scope.project.push({id: 0, name: " Select Project", proj_status: "active"});
        res = $scope.$root.sort(res, "proj_name");
        res = res.filter(proj => proj.proj_status === "active");
        res.map((o) => $scope.project.push({id: o.projectid, name: o.proj_name, proj_status: o.proj_status, proj_mydiaryLockDate: o.proj_mydiaryLockDate}));
        $scope.filter.project = $scope.project[0];
      }
    };
    $scope.clickSelectAll = function () {
      angular.forEach($scope.myDiary.default, function (value) {
        value.selected = $scope.selectAll.selected;
        if ($scope.selectAll.selected) {
          if ($scope.CheckedId.length == 0) {
            $scope.CheckedId = value.mydiaryid;
          }
          else {
            $scope.CheckedId += ", " + value.mydiaryid;
          }
        }
      });
      if (!$scope.selectAll.selected) $scope.CheckedId = "";
    };
    $scope.updateLockedDate = function () {
      if (!$scope.myDiaryLock.LockTillDate) toastr.error("Please provide valid Date to Lock.");
      else vServices.callApi("mydiary/lock", "PUT", {proj_id: $scope.filter.project.id, lock_date: $scope.myDiaryLock.LockTillDate}).then((res) => {
        if (res) {
          //toastr.success(res, "Message");
        }
        $state.go($state.current, {}, {reload: true});
      });
    };
    $scope.Checked = function () {
      $scope.CheckedId = "";
      $scope.selectAll.selected = true;
      angular.forEach($scope.myDiary.default, function (value) {
        if (value.selected) {
          if ($scope.CheckedId.length == 0) {
            $scope.CheckedId = value.mydiaryid;
          }
          else {
            $scope.CheckedId += ", " + value.mydiaryid;
          }
        }
        else $scope.selectAll.selected = false;
      });
    };

    const convertDataForMyDiary = res => {
      if (res) {
        let newResult = null, newResult1 = null, resHero = null;
        $scope.myDiary.datatable.map((o) => {
          o.destroy();
        });
        // remove date from header
        document.querySelectorAll("#myDiaryDataTableView thead tr th.datehead").forEach(o => o.remove());

        $scope.myDiary = {default: [], project: [], heroes: [], datatable: []};
        let res1 = $scope.$root.sort(res, "emp_first_name");
        $scope.myDiary.default = $scope.$root.sort(res1, "proj_name");

        newResult = res.map(o => o.proj_name + "~" + o.projectid).filter((v, i, s) => s.indexOf(v) === i).sort();

        newResult.forEach(o => {
          const proj = o.split("~");
          $scope.myDiary.project.push({name: proj[0], id: proj[1], data: res.filter(j => j.projectid === parseInt(proj[1]))});
        });

        newResult1 = res.map(o => o.emp_first_name + " " + o.emp_last_name + "-" + o.employeeid).filter((v, i, s) => s.indexOf(v) === i).sort();
        resHero = $scope.$root.sort(res, "projectid");
        newResult1.forEach(o => {
          const hero = o.split("-");
          $scope.myDiary.heroes.push({name: hero[0], id: hero[1], data: resHero.filter(j => j.employeeid === parseInt(hero[1]))});
        });
        $scope.tblheader = [];

        // res[0].logged_hours.forEach((o)=>{
        //     console.log(o);
        // })
        var headerLength = 1;
        for (var k in res[0].logged_hours) {
          try {
            headerLength++;
            var node = document.createElement("th");                // Create a <li> node
            var textnode = document.createTextNode(k);              // Create a text node
            node.setAttribute("class", "datehead");
            node.appendChild(textnode);                             // Append the text to <li>
            //document.getElementById("myList").appendChild(node);    // Append <li> to <ul> with id="myList"

            document.querySelector("#myDiaryDataTableView thead tr").appendChild(node);
          }
          catch (e) {
            console.error(e);
          }
          //console.log(k, res[0].logged_hours[k]);
        }

        $scope.$root.callDataTable("#myDiaryDataTableView", headerLength * 100, (t) => {
          $scope.myDiary.datatable.push(t);
        }, {orientation: "landscape"});

        // $scope.tblheader = (res[0].logged_hours);
        // console.table($scope.tblheader);

      }
      setTimeout(() => {
        $scope.tooltip();
      }, 1000);
    };

    const getData = (f, t, h) => vServices.callApi("mydiary/unfilled?date=" + f + "&todate=" + t + "&minHours=" + h, "GET", {}).then(res => convertDataForMyDiary(res));
    $scope.dateChanged = (first = false) => {
      if (!first) {
        $scope.showLockDiv = $scope.filter.project.id > 0 ? true : false;
        if (!$scope.filter.fromDate) toastr.error("Please provide valid FromDate");
        else if (!$scope.filter.toDate) toastr.error("Please provide valid toDate");
        else getData($scope.filter.fromDate, $scope.filter.toDate, $scope.filter.minHours);
      }
    };

    const init = () => {
      getData();

    };

    init();

  }]);
