

/* Controllers */

/*------------------------------------------------------------------------------------- */
/*-- Sidebar Controller --------------------------------------------------------------- */
/*------------------------------------------------------------------------------------- */
function SidebarCtrl($scope, $location, storageManager) {

  $scope.location = $location;
  $scope.characterCount = 0;

  //decide if a link should be active based on the current location
  $scope.isActive = function (viewLocation) {
    return (viewLocation === $location.path());
  },

  $scope.changeView = function(view){
    $location.path(view);
  },

  $scope.$on('lessonsLoaded', function(event) {
    for (var i = 1; i <= 6; i++){
      $scope["lesson"+i] = false;		
    }
    var lessons = storageManager.getSelectedLessons();
    for (var i = 0; i < lessons.length; i++) {
      $scope[lessons[i]] = true;
    }
    $scope.characterCount = storageManager.getCharacterCount();
  }),

  $scope.toggleLessonSelection = function(lesson) {
    $scope[lesson] = !$scope[lesson];    
    var selectedLessons = [];
    for (var i = 1; i <= 6; i++){
      if($scope["lesson"+i]){
        selectedLessons.push("lesson"+i);
      };		
    }

    if(selectedLessons.length == 0){
      $scope[lesson] = true;
      //TODO show error
    } else {
      storageManager.setSelectedLessons(selectedLessons);    
      $scope.characterCount = storageManager.getCharacterCount();
    }
  }

  $scope.toggleSidebar = function(){
    $scope.showSidebar = !$scope.showSidebar;
  }
}


/*------------------------------------------------------------------------------------- */
/*-- Kana Table Controller ------------------------------------------------------------ */
/*------------------------------------------------------------------------------------- */
function KanaTableCtrl($scope, $location, storageManager) {

  $scope.characterType = 'hiragana';
  $scope.orientation = window.innerWidth > window.innerHeight ? 'landscape' : 'portrait';

  angular.element(window).bind('resize',function(){
    //detect orientation changes
    var orientation = window.innerWidth > window.innerHeight ? 'landscape' : 'portrait';
    if(orientation != $scope.orientation){
      $scope.orientation = orientation;
      $scope.$apply();
    }
  });

  $scope.toggleCharacterType = function(characterType) {
    $scope.characterType = characterType;
  }

}


/*------------------------------------------------------------------------------------- */
/*-- Statistics Controller ------------------------------------------------------------ */
/*------------------------------------------------------------------------------------- */
function StatisticsCtrl($scope, $location, storageManager) {
  $scope.trainingStatistics = storageManager.trainingStatistics;
  $scope.chartOptions =  {
    // Chart.js options can go here.
      scaleOverlay : false,
      scaleOverride : true,
      scaleSteps : 5,
      scaleStepWidth : 20,
      scaleStartValue : 0,
      scaleLineColor : "rgba(256,256,256,.5)",
      scaleLineWidth : 2,
      scaleShowLabels : true,
      scaleLabel : "<%=value%>%",
      scaleFontFamily : "'Arial'",
      scaleFontSize : 22,
      scaleFontStyle : "normal",
      scaleFontColor : "#666",
      scaleShowGridLines : false,
      scaleGridLineColor : "rgba(256,256,256,.5)",
      scaleGridLineWidth : 1,
      bezierCurve : true,
      pointDot : true,
      pointDotRadius : 4,
      pointDotStrokeWidth : 2,
      datasetStroke : true,
      datasetStrokeWidth : 2,
      datasetFill : true,
      animation : true,
      animationSteps : 60,
      animationEasing : "easeOutQuart",
      onAnimationComplete : null
  };
  var chartCanvas = document.getElementById("chartCanvas");
  var toolbarHeight = (document.getElementById("toolbar")).clientHeight || 0;
  var mainHeight = (document.getElementById("main-content")).clientHeight || window.innerHeight;
  chartCanvas.width = window.innerWidth;
  chartCanvas.height = mainHeight - 2*toolbarHeight;
  if(storageManager.trainingStatisticsHistory.length > 0){
    var data = [];
    var labels = [];
    for (var i = 0; i < storageManager.trainingStatisticsHistory.length; i++){
      var statsItem = storageManager.trainingStatisticsHistory[i];
      // console.log("history item:" + statsItem.right + " wrong:" + statsItem.wrong);
      data.push(Math.round((statsItem.right / (statsItem.right + statsItem.wrong))*100));
      labels.push('');
    }
    $scope.chartData = {
      labels: labels,
      datasets : [
      {
        fillColor : 'rgba(151,187,205,0.4)',
        strokeColor : 'rgba(151,187,205,1)',
        pointColor : 'rgba(151,187,205,1)',
        data : data
      }]};
  }
}

/*------------------------------------------------------------------------------------- */
/*-- Memory Exercise Controller ------------------------------------------------------- */
/*------------------------------------------------------------------------------------- */
function MemoryCtrl($scope,  $location, storageManager) {

  $scope.trainingStatistics = storageManager.trainingStatistics;
  $scope.inverseQuestion = false;
  $scope.resetMemory = function() {
    //console.log("reset memory");

    var dejavu = {};

    for (var i = 1; i < 6; i++){
      var c = storageManager.getRandomEntry(dejavu);
      c.wrong = c.right = false;
      $scope["box"+i] = c;		
      dejavu[c.symbol]=true;
    }

    //choose one characterEntry to go in box 0
    var random = Math.floor(Math.random()*4)+1;
    $scope.box0 = $scope["box"+ random];
    $scope.box0.retry = 0;

    //mark the right boxes
    for (var i = 1; i < 6; i++){
      var c = $scope["box"+i];
      if(c == $scope.box0){
        c.right = true;
      }
    }


  } 

  $scope.onBoxSelection = function(box) {
    if(!$scope.box0){
      return;
    }

    if($scope.box0.symbol == box.symbol){
      box.right = true;
      if(!$scope.box0.retry){
        //only first attempt is counted
        storageManager.markAsRight($scope.box0);

      }
      $scope.resetMemory();
    } else {				
      if(!$scope.box0.retry){
        //only first attempt is counted
        storageManager.markAsWrong($scope.box0);
      }
      box.wrong = true;
      $scope.box0.retry = true;
    }    

  }

  $scope.onResetSession = function() {
    storageManager.resetStatistics();
    $scope.resetMemory();
  }

  $scope.$on('lessonsLoaded', function(event) {
    $scope.resetMemory();
  })

  if(storageManager.getActiveCharacterCount() > 0){
    $scope.resetMemory();
  }
};


/*------------------------------------------------------------------------------------- */
/*-- Drawing Exercise Controller ------------------------------------------------------ */
/*------------------------------------------------------------------------------------- */
function DrawCtrl($scope, $location, storageManager) {

  $scope.answerShowing = false;  
  $scope.trainingStatistics = storageManager.trainingStatistics;

  var dejavu = {};  
  var answer; 
  var answerFont = window.innerHeight/3 + "px sans";
  var animCharacter;
  
  var bgcanvas = document.getElementById("bgcanvas");
      bgcanvas.width = window.innerWidth;
      bgcanvas.height = window.innerHeight;
  var bgStage = new createjs.Stage(bgcanvas);
  var canvas = document.getElementById("canvas");

 

  var oldPt;
  var oldMidPt;
  var title;
  var color = "rgba(0,171,204,1)";
  var stroke = 10;
  var animCharacter;

  var stage;
  var drawingCanvas;
  
  var firstMouseDown = true;  
  
  $scope.init = function(){
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    if(storageManager.getActiveCharacterCount() > 0){
      $scope.resetDraw();
    }
  }

  function setupDrawingCanvas() {
    stage = new createjs.Stage(canvas);
    stage.autoClear = false;
    stage.enableDOMEvents(true);
    createjs.Touch.enable(stage);
    createjs.Ticker.setFPS(24);

    drawingCanvas = new createjs.Shape();

    stage.addEventListener("stagemousedown", handleMouseDown);
    stage.addEventListener("stagemouseup", handleMouseUp);

    stage.addChild(drawingCanvas);
    stage.clear();
    stage.update();
  }

  function handleMouseDown(event) {
    if(firstMouseDown){
      //this is a fix a strange bug in FxOS
      firstMouseDown = false;
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
    }
    oldPt = new createjs.Point(stage.mouseX, stage.mouseY);
    oldMidPt = oldPt;
    stage.addEventListener("stagemousemove" , handleMouseMove);
    // stage.addEventListener("touchmove", handleMouseMove);
  }

  function handleMouseMove(event) {
    var midPt = new createjs.Point(oldPt.x + stage.mouseX>>1, oldPt.y+stage.mouseY>>1);
    drawingCanvas.graphics.clear().setStrokeStyle(stroke, 'round', 'round').beginStroke(color).moveTo(midPt.x, midPt.y).curveTo(oldPt.x, oldPt.y, oldMidPt.x, oldMidPt.y);

    oldPt.x = stage.mouseX;
    oldPt.y = stage.mouseY;

    oldMidPt.x = midPt.x;
    oldMidPt.y = midPt.y;

    stage.update();
  }

  function handleMouseUp(event) {
    stage.removeEventListener("stagemousemove" , handleMouseMove);
    //  stage.removeEventListener("touchmove", handleMouseMove);
  }


  $scope.resetDraw = function() {
    if(animCharacter != null){
      bgStage.removeChild(animCharacter);
      animCharacter = null;
    }
    if(answer != null){
      bgStage.removeChild(answer); 
      answer = null;
    }
    bgStage.clear();
    $scope.answerShowing = false;  
    $scope.currentCharacter = storageManager.getRandomEntry(dejavu);
    setupDrawingCanvas();
  } 

  $scope.onDone = function() {

    if (!$scope.answerShowing){
      var animation = $scope.currentCharacter.anim;
      if (animation){
        LazyLoad.js('js/animations/' + animation + '.js', function () {
          animCharacter = new lib[animation](null,null,false);
          var ratio = (window.innerHeight/290)*1;
          var offset;


          if($scope.currentCharacter.symbol.length == 2){
            if(window.innerWidth > window.innerHeight){
              offset = window.innerWidth * 0.3;
            }else{
              offset = 0;
            }
            animCharacter.x =  -20 + offset;
            animCharacter.y = 40;
            ratio = (window.innerHeight/340)*1;
          } else {
            if(window.innerWidth > window.innerHeight){
              offset = window.innerWidth * 0.3;
            }else{
              offset = window.innerWidth * 0.05;
            }
            animCharacter.x = 40 + offset;
            animCharacter.y = 30;
            ratio = (window.innerHeight/290)*1;
          }

          animCharacter.scaleX = animCharacter.scaleY = ratio;
          bgStage.autoClear = true;
          bgStage.addChild(animCharacter);
          bgStage.update();

          createjs.Ticker.setFPS(8);
          createjs.Ticker.addEventListener("tick", bgStage);

        });

      } else {

        var ratio = (window.innerHeight/280)*1;
        answer = new createjs.Text($scope.currentCharacter.symbol, answerFont, "#666666");
        answer.x = 30; //TODO center text
        answer.y = 60;
        bgStage.addChild(answer);
        bgStage.update();
        //        labelDone.text = currentCharacter.answer;
      }
      $scope.answerShowing = true;

    } else {
      $scope.resetDraw();
    }
  }

  $scope.onMarkRight = function() {
    storageManager.markAsRight($scope.currentCharacter);
    $scope.resetDraw();
  }

  $scope.onMarkWrong = function() {
    storageManager.markAsWrong($scope.currentCharacter);
    $scope.resetDraw();
  }

  $scope.onResetSession = function() {
    storageManager.resetStatistics();
    $scope.resetDraw();
  }

  $scope.$on('lessonsLoaded', function(event) {
    $scope.resetDraw();
  })

}
