'use strict';
var angular = require('angular');
require('../modules');
require('ngIonic');
require('../services/GraphicsDrawContext');

var module = angular.module('gesturepassword.directives.screen');
module.directive('gesturePasswordScreenThumbnail',
  function($parse, $rootScope, GraphicsDrawContext) {

  function getCircles() {
    var circles = [],
      circle, radius = 4;
    for (var i = 0; i < 9; i++) {
      var relativeX = i % 3,
      relativeY = Math.floor(i / 3);
      circle = {
        x: 1 + radius + 3 * radius * relativeX,
        y: 1 + radius + 3 *  radius * relativeY
      };
      circles.push(circle);
    }
    return circles;
  }

  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var screenContext = $parse(attrs.screenContext)(scope),
        canvas = element[0],
        ctx = canvas.getContext('2d'),
        ratio = window.devicePixelRatio,
        circles = getCircles();

      canvas.width = 34 * ratio;
      canvas.height = 34 * ratio;
      ctx.scale(ratio, ratio);
      ctx.fillStyle = GraphicsDrawContext.NORMAL_STROKE_COLOR;
      ctx.strokeStyle = GraphicsDrawContext.DEFAULT_STROKE_COLOR;
      var currentSelectors;

      function render() {
        var selectors = (screenContext.firstpassword || '').split(''),
          circle;
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

        ctx.beginPath();
        for (var i = 0; i < 9; i++) {
          circle = circles[i];
          ctx.moveTo(circle.x + 4, circle.y);
          ctx.arc(circle.x, circle.y, 4, 0, Math.PI * 2);
        }
        ctx.stroke();

        ctx.beginPath();
        for (var i = 0, len = selectors.length; i < len; i++) {
          circle = circles[selectors[i]];
          ctx.moveTo(circle.x + 4, circle.y);
          ctx.arc(circle.x, circle.y, 4, 0, Math.PI * 2);
        }
        ctx.fill();
      }

      $rootScope.$on('$gesturepassword.updatefirstpassword', function() {
        render();
      });
      render();
    }
  };
});