angular.module('pomodoro', [])
  .controller('PomodoroController', function($scope, $interval) {
    $scope.breakDisp = 5;
    $scope.sessionDisp = 15;
    $scope.resDispText = "SESSION: ";
    $scope.resDispNum = 15;
    $scope.progressBar = 0;
    $scope.progressColor = "green";
    $scope.clockStarted = false;

    $scope.incNum = function(num, type) {
      num = num + 1;

      if(type === "break") {
        $scope.breakDisp = num;
        $scope.resDispText = "BREAK: ";
        $scope.resDispNum = num;
      } else if(type === "session") {
        $scope.sessionDisp = num;
        $scope.resDispText = "SESSION: ";
        $scope.resDispNum = num;
      }
    }

    $scope.decNum = function(num, type) {
      if(num > 1) {
        num = num - 1;
      } else {
        num = num;
      }

      if(type === "break") {
        $scope.breakDisp = num;
        $scope.resDispText = "BREAK: ";
        $scope.resDispNum = num;
      } else if(type === "session") {
        $scope.sessionDisp = num;
        $scope.resDispText = "SESSION: ";
        $scope.resDispNum = num;
      }
    }

    $scope.start = function(num, type) {
      $scope.clockStarted = true;
      let progressUnit = 0;
      let progressMeter = 0;
      let timer = moment.duration(num, "minutes").timer({
        loop: false,
        start: false
      }, function() {
        // Callback
      });
      let timerRefresh;

      if(type === "session") {
        $scope.resDispText = "SESSION: ";
        $scope.resDispNum = $scope.sessionDisp;
      } else if(type === "break") {
        $scope.resDispText = "BREAK: ";
        $scope.resDispNum = $scope.breakDisp;
      }
      let resWatcher = $scope.$watch('resDispNum', function(newValue, oldValue) {
        if(type === "session") {
          progressUnit = 100 / ($scope.sessionDisp * 60);
          progressMeter = progressMeter + progressUnit;
          $scope.progressColor = "green";
        } else if (type === "break") {
          progressUnit = 100 / ($scope.breakDisp * 60);
          progressMeter = progressMeter + progressUnit;
          $scope.progressColor = "red";
        }
        $scope.progressBar = progressMeter;
      });

      timer.start();
      timerRefresh = $interval(function() {
        $scope.resDispNum = moment(timer.getRemainingDuration()).format("mm:ss");
        if(type === "session" && $scope.resDispNum === "00:00") {
          timer.stop();
          $interval.cancel(timerRefresh);
          $scope.start($scope.breakDisp, "break");
        } else if(type === "break" && $scope.resDispNum === "00:00") {
          timer.stop();
          $interval.cancel(timerRefresh);
          $scope.start($scope.sessionDisp, "session");
        }
      }, 500);

      $scope.stop = function() {
        timer.stop();
        $interval.cancel(timerRefresh);
        resWatcher();
        $scope.clockStarted = false;
      }
    }

  });
