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

var module = angular.module('meet');

module.controller('MeetGroupCtrl', function($scope, MeetService,
  $ionicScrollDelegate, $timeout) {

  var ctrl = this;
  ctrl.init = init;
  ctrl.preWeek = getPreWeek;
  ctrl.nextWeek = getNextWeek;
  ctrl.getItemStyle = getItemStyle;

  $scope.meetDateTab = true;

  var scrollView = $ionicScrollDelegate.$getByHandle('meetScrollView');

  $scope.$on('$ionicView.beforeEnter', function() {
    init();
  });

  function init() {
    getData();
  }

  function getItemStyle(item) {

    var styles = {
      'border-left-color': item.color
    };
    return styles;
  }
  function getPreWeek() {
    ctrl.dropdown = !ctrl.dropdown;
    scrollView.scrollTo(0, 0);
    getData('last', ctrl.perWeekDate);
  }

  function getNextWeek() {
    ctrl.dropdown = !ctrl.dropdown;
    scrollView.scrollTo(0, 0);
    getData('next', ctrl.nextWeekDate);
  }

  function getData(weekFlag, date) {
    ctrl.loading = true;
    ctrl.loadingState = 1;
    ctrl.showMore = true;
    return MeetService.getWeekOfMeet(weekFlag, date).then(function sucess(data) {
      ctrl.meets = data.content;
      ctrl.isPreWeek = data.isPreWeek;
      ctrl.isNextWeek = data.isNextWeek;
      ctrl.perWeekDate = data.perWeekDate;
      ctrl.nextWeekDate = data.nextWeekDate;
      ctrl.weekCount = data.weekCount;
      ctrl.leader = data.leader;
      ctrl.loadingState = _.isEmpty(ctrl.meets) ? 4 : 2;
      if( !ctrl.isPreWeek && !ctrl.isNextWeek) {
        ctrl.showMore = false;
      }
      $timeout(function() {
        ctrl.loading = false;
      }, 300);
    }, function error() {
      ctrl.loadingState = 3;
      ctrl.loading = false;
    });
  }

});
