/**
 * thenDate가 nowDate보다 얼마나 이전인지 계산하여, 규격화된 문자열 형태로 반환한다. 규칙은 아래와 같다.
 *
 * 3분 미만 : 방금
 * 3분 ~ 1시간 미만 : N분
 * 1시간 ~ 24시간 미만 : N시간
 * 1일 ~ 7일 미만 : N일
 * 7일 ~ : 날짜
*/

const MIN_SECONDS = 60;
const HOUR_SECONDS = MIN_SECONDS * 60;
const DAY_SECONDS = HOUR_SECONDS * 24;
const WEEK_SECONDS = DAY_SECONDS * 7;


const YEAR = '년';
const MONTH = '월';
const HOUR = '시';
const Second = '초';
const DAY_BEFORE = '일';
const HOUR_BEFORE = '시간';
const MIN_BEFORE = '분';
const JUST_BEFORE = '방금';


const getPeriodTimeString = (produceDate: string) => {
  const nowDate = new Date();
  const thenDate = new Date(produceDate);
  const timeGap = (nowDate.getTime() - thenDate.getTime());

  const utcNow = thenDate.getTime() + (thenDate.getTimezoneOffset() * 60 * 1000);
  const koreaTimeDiff = 9 * 60 * 60 * 1000;
  const updateDate = new Date(utcNow + (koreaTimeDiff))


  if (inWeeksOf(timeGap) > 0) {
    return `${updateDate.getFullYear()}${YEAR}` + ' ' + `${updateDate.getMonth() + 1}${MONTH}` + ' ' + `${updateDate.getDate()}${DAY_BEFORE}` + ' ' + `${updateDate.getHours()}${HOUR}` + " " + `${updateDate.getMinutes()}${MIN_BEFORE}`
  }
  if (inDaysOf(timeGap) > 0) {
    return inDaysOf(timeGap) + DAY_BEFORE;
  }
  if (inHoursOf(timeGap) > 0) {
    return inHoursOf(timeGap) + HOUR_BEFORE;
  }
  if (inMinutesOf(timeGap) > 2) {
    return inMinutesOf(timeGap) + MIN_BEFORE;
  }

  return JUST_BEFORE;
};

const inSecondsOf = (timeGap: number) => {
  return (timeGap / 1000);
};

const inMinutesOf = (timeGap: number) => {
  return Math.floor(inSecondsOf(timeGap) / MIN_SECONDS);
};

const inHoursOf = (timeGap: number) => {
  return Math.floor(inSecondsOf(timeGap) / HOUR_SECONDS);
};

const inDaysOf = (timeGap: number) => {
  return Math.floor(inSecondsOf(timeGap) / DAY_SECONDS);
};

const inWeeksOf = (timeGap: number) => {
  return Math.floor(inSecondsOf(timeGap) / WEEK_SECONDS);
};

export default {
  getPeriodTimeString
};
