import moment from 'moment';
import { SettlementDays, SettlementStatus } from '../model/types';

export interface CalendarGridProps {
  yearMonth: string;
  settlementDays: Array<SettlementDays | undefined>
};

export const CalendarGrid = ({
  yearMonth,
  settlementDays
}: CalendarGridProps) => {

  const checkData = (val: number) => {
    let rs: SettlementStatus | undefined;
    for(let i=0;i<settlementDays.length;i++){
      let date = moment(settlementDays[i]?.settlementDate).date();
      if(val === date){
        rs = settlementDays[i]?.settlementStatus;
        break;
      }
    }
    return rs;
  };

  const makeCalendarDate = () => {
    let startDay = moment(yearMonth).startOf('month').day();
    let lastDate = moment(yearMonth).endOf('month').date();
    let lastYearMonth = moment(yearMonth).subtract(1, 'month').format('YYYY-MM');
    let lastYearMonthLastDate = moment(lastYearMonth).endOf('month').date();

    let lastOthersCnt = (7 - ((startDay + lastDate) % 7));

    let rs = [];
    for(let i=0;i<startDay;i++){
      rs.push(
        <div className="day other">{ (lastYearMonthLastDate - startDay + i + 1) }</div>
      );
    }
    for(let i=1;i<=lastDate;i++){
      let ck = checkData(i);
      if(ck === SettlementStatus.SCHEDULED){
        rs.push(
          <div className="day scheduled">{ i }</div>
        );
      }
      else if(ck === SettlementStatus.COMPLETED){
        rs.push(
          <div className="day complete">{ i }</div>
        );
      }
      else{
        rs.push(
          <div className="day">{ i }</div>
        );
      }
    }
    for(let i=0;i<lastOthersCnt;i++){
      rs.push(
        <div className="day other">{ (i + 1) }</div>
      );
    }
    
    return rs;
  }

  return (
    <>
      <div className="calendar-grid">
        <div className="weekdays">
          <div className="weekday sun">일</div>
          <div className="weekday">월</div>
          <div className="weekday">화</div>
          <div className="weekday">수</div>
          <div className="weekday">목</div>
          <div className="weekday">금</div>
          <div className="weekday sat">토</div>
        </div>
        <div className="days">
        { makeCalendarDate() }
        </div>
      </div>
    </>
  )
};