'use strict';

var angular = require('angular'),
  _ = require('jsUtil');
require('../modules');

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

var ONE_DAY_MILLISECONDS = 24 * 60 * 60 * 1000;

module.factory('Meet', function() {
  var day = new Date().getDate();

  var service = {
    getOpenDate: getOpenDate,
    sortMeet: sortMeet,
    getNowDate: getNowDate,
    getColor: getColor
  };

  /**
   * 为了单元测试
   */
  function getNowDate(simulationDate) {
    var _date;
    if(simulationDate) {
      _date = simulationDate;
    }else {
      _date = new Date();
    }

    var _month = _date.getMonth() + 1,
      _day = _date.getDate(),
      month = _month < 10 ? '0' + _month : _month,
      day = _day < 10 ? '0' + _day : _day,
      nowDate = _date.getFullYear() + '-' + month + '-' + day;
    return nowDate;
  }

  function sortMeet(data, openDate) {
    if(_.isEmpty(openDate)) {
      openDate = getNowDate();
    }

    var meets = [], meet = [];
    var dateMap = {};
    _.each(data, function(item) {
      item.color = getColor(item.meetDate.substring(0, 10), openDate);
      dateMap[item.meetDate] = item.meetDate;
    });

    _.each(dateMap, function(list, meetDate) {
      meet = [];
      _.each(data, function(item) {
        if(item.meetDate == list) {
          meet.push(item);
        }
      });
      meets.push({
        date: list,
        meets: meet
      });
    });

    return getDefuleOpen(meets, openDate);
  }

  function getDefuleOpen(meets, openDate) {

    var dates = [];
    _.each(meets, function(meet) {
      dates.push(meet.date.substring(0, 10));
    });
    var defaultOpenDate = getOpenDate(dates, openDate);
    _.each(meets, function(meet) {
      meet.open = meet.date.substring(0, 10) == defaultOpenDate ? true : false;
    });
    return meets;
  }

  function getOpenDate(dates, openDate) {
    var latestLessDate = dates[0], latestLargeDate = dates[0];
    for (var i = 0, len = dates.length; i < len; i++) {
      if (dates[i] < openDate) {
        latestLessDate = dates[i];
      } else if (dates[i] > openDate) {
        return dates[i];
      } else if (dates[i] === openDate) {
        return dates[i];
      }
    }
    return latestLessDate;
  }

  function getColor(meetDate, openDate) {
    var _color;
    if(meetDate === openDate) {
      _color = '#C66363';//红色
    } else if(meetDate < openDate) {
      _color = '#65AFB6';//绿色
    } else {
      _color = '#537BC7';//蓝色
    }
    return _color;
  }

  return service;
});
