import * as _ from 'lodash';
import moment from 'moment';

export interface IDayCalendar {
   day: number;
   month: number;
   year: number;
   today: boolean;
   date: string;
   dateYYYYMMDD: string;
   currentMonth: boolean;
   nextMonth: boolean;
   lastMonth: boolean;
   dateInstance: Date;
}

export type IMonthCalendar = IDayCalendar[][];

class CalendarService {
   // public weeksName = ['DOM', 'SEG', 'TER', 'QUA', 'QUI', 'SEX', 'SAB'];
   public weeksName = ['D', 'S', 'T', 'Q', 'Q', 'S', 'S'];

   public monthsName = [
      'Janeiro',
      'Fevereiro',
      'Março',
      'Abril',
      'Maio',
      'Junho',
      'Julho',
      'Agosto',
      'Setembro',
      'Outubro',
      'Novembro',
      'Dezembro',
   ];

   /**
    * Retorna Mês do calendário, com mês atual, anterior e proximo
    * @param {number} month
    * @param {number} year
    */
   getMonth(month: number, year: number): IMonthCalendar {
      const monthMoment = moment().date(1).month(month).year(year);
      const currentMonth = monthMoment.month();
      const nextMonth = moment(monthMoment).add(1, 'M').month();
      const previousMonth = moment(monthMoment).subtract(1, 'M').month();

      monthMoment.subtract(monthMoment.day(), 'day');

      const today = moment().format('DD/MM/YYYY');
      const days: IDayCalendar[] = [];
      for (let i = 0; i < 7 * 6; i += 1) {
         days.push({
            day: monthMoment.date(),
            month: monthMoment.month() + 1,
            year: monthMoment.year(),
            today: today === monthMoment.format('DD/MM/YYYY'),
            date: monthMoment.format('DD/MM/YYYY'),
            dateInstance: monthMoment.toDate(),
            dateYYYYMMDD: monthMoment.format('YYYYMMDD'),
            lastMonth: previousMonth === monthMoment.month(),
            currentMonth: currentMonth === monthMoment.month(),
            nextMonth: nextMonth === monthMoment.month(),
         });

         monthMoment.add(1, 'day');
      }

      return _.chunk(days, 7);
   }
}

export const Calendar = new CalendarService();
