app.service('$holiday', function ($date) {
  this.getDayHolidays = function (holidays, day) {
    var holidaysToday = [];

    for (var i = 0; i < holidays.length; i++) {
      if (!this.dayMatch(holidays[i].holiday, day)) {
        continue;
      }
      holidaysToday.push(holidays[i].holiday);
    }

    return holidaysToday;
  };

  this.dayMatch = function (holiday, thisDay) {
    if (!(thisDay instanceof Date)) {
      thisDay = new Date(thisDay);
    }
    var dayToday = thisDay.getDate();
    var monthToday = thisDay.getMonth() + 1;

    var date = calculateNextOccurrence(holiday);
    return (dayToday === date.getDate() && monthToday === date.getMonth() + 1);
  };

  this.calculateNextOccurrence = function (holiday) {
    return $date.formatDate(calculateNextOccurrence(holiday));
  };

  function calculateNextOccurrence() {
    var date;
    var currentYear = new Date().getFullYear();

    switch (holiday.format) {
      case 'static':
        var day = holiday.date.split('/')[0];
        var month = holiday.date.split('/')[1];
        date = new Date(currentYear + '/' + month + '/' + day);

        if (new Date() >= date) {
          date = new Date((currentYear + 1) + '/' + month + '/' + day);
        }

        break;

      case 'dynamic':
        eval('my_function = ' + holiday.formula);
        if (typeof my_function !== 'function') {
          return;
        }
        date = my_function(currentYear);
        if (date < new Date()) {
          date = my_function(currentYear + 1);
        }
        break;
    }

    return date;
  }
});
