'use strict';
var angular = require('angular');
require('../modules');
var module = angular.module('gesturepassword.services');

module.factory('GraphicsStateContext', function() {

  function GraphicsStateContext(screenContext){
    this.screenContext = screenContext;
    this.circles = screenContext.pointers;
    this.width = screenContext.width;
    this.height = screenContext.height;
    this.selectCircles = _.map(screenContext.selectors, function(index) {return screenContext.pointers[index];});
    this.lines = GraphicsStateContext.generateLines(this.selectCircles, this.screenContext.movingPointer);
    this.directionIndicators = GraphicsStateContext.generateDirectionIndicators(this.selectCircles);
  }

  GraphicsStateContext.generateDirectionIndicators = function(circles) {
    var indicators = [], circle, i, rotate;
    for (i = 0; i <= circles.length - 2; i++) {
      circle = circles[i];
      rotate = GraphicsStateContext.computerDegree(circle, circles[i + 1]);
      indicators.push({
        x: circle.x,
        y: circle.y,
        rotate: rotate,
        scale: circle.scale || 1
      });
    }
    return indicators;
  };

  GraphicsStateContext.computerDegree = function(pointerA, pointerB) {
    var offsetPointB = {x: pointerB.x - pointerA.x, y: pointerB.y - pointerA.y},
      quadrant = GraphicsStateContext.getQuadrant(offsetPointB);//计算所在的象限

    if (offsetPointB.x === 0) {
      return offsetPointB.y > 0? 90 : 270;
    } else if (offsetPointB.y === 0) {
      return offsetPointB.x > 0? 0 : 180;
    } else {
      var degree = Math.atan(Math.abs(offsetPointB.y / offsetPointB.x)) * 180 / Math.PI;
      if (quadrant === 1 || quadrant === 3) {
        degree = 90 - degree;
      }
      return quadrant * 90 + degree;
    }

  };

  GraphicsStateContext.getQuadrant = function(pointer) {
    var x = pointer.x > 0,
      y = pointer.y > 0;
    return x && y? 0 : !x && y? 1 : !x && !y? 2 : 3;
  };

  GraphicsStateContext.generateLines = function(circles, endPointer) {
    var lines = [], line, i;
    var pointers = endPointer? circles.concat(endPointer) : circles;
    for (i = 1; i < pointers.length; i++) {
      line = {
        start: {x: pointers[i - 1].x, y: pointers[i - 1].y},
        end: {x: pointers[i].x, y: pointers[i].y}
      };
      line.rotate = GraphicsStateContext.computerDegree(line.start, line.end);
      lines.push(line);
    }
    return lines;
  };

  return GraphicsStateContext;

});
