var angular = require('angular');
require('../modules');
require('jsUtil');
require('../services/Timer');

var module = angular.module('commons.directives.sinoTabs');

module.directive('sinoTabs', function(Timer) {
  return {
    restrict: 'A',
    template: '<div class="segmented-control" ng-transclude></div>',
    scope: {
      moduleName: '=sinoTabs',
      tabChange: '=sinoTabChange'
    },
    replace: true,
    transclude: true,
    link: function(scope, element) {
      function init() {
        scope.tabs = element.find('a') || element.find('button');
        if (!scope.tabs.length) { return; } 
        scope.tabMap = window.localStorage.tabMap ? JSON.parse(window.localStorage.tabMap) : {};
        scope.selectItem = scope.tabMap[scope.moduleName];
        onClick();
        scope.change(scope.selectItem || scope.tabs[0].getAttribute('tab-name'), true);
      }
      
      scope.change = function(item, first) {
        if (item !== scope.selectItem || first) {
          scope.selectItem = item;
          scope.tabMap[scope.moduleName] = scope.selectItem;
          window.localStorage.tabMap = JSON.stringify(scope.tabMap);
          addActiveClass();
          scope.tabChange(scope.selectItem);
        }
      }

      function onClick() {
        _.each(scope.tabs, function(tab) {
          tab.onclick = function(event) {
            scope.change(tab.getAttribute('tab-name'));
            event.preventDefault();
            event.stopPropagation();
          };
        });
      }

      function addActiveClass() {
        _.each(scope.tabs, function(tab) {
          if (tab.getAttribute('tab-name') === scope.selectItem) {
            tab.setAttribute('class','control-item active');
          } else {
            tab.setAttribute('class','control-item');
          }
        });
      }

      Timer.delay(function() { init(); });
    }
  };
});
