import moment from 'moment';

export class AppUtils {
  public static dateFormat(date: Date, format: string): any {
    if (!date) {
      return null;
    }
    return moment(date).format(format);
  }

  public static convertDate(str: string, format?: string, substring?: boolean) {
    if (str) {
      const data = moment(substring && format ? str.substring(0, format.length) : str, format);
      if (data.isValid()) {
        return data.toDate();
      }
    }

    return null;
  }

  public static calAge(birth: string | Date, format?: string) {
    let birthday;
    if (typeof birth == 'string') {
      birthday = this.convertDate(birth, format);
    } else {
      birthday = birth;
    }

    if (birthday) {
      const now = new Date();
      let age = now.getFullYear() - birthday.getFullYear();
      if (now.getMonth() < birthday.getMonth() || (now.getMonth() == birthday.getMonth() && now.getDay() < birthday.getDay())) {
        age--;
      }

      return age < 0 ? 0 : age;
    }
    return null;
  }

  public static isNull(val: any) {
    if (val === null || val === undefined || val === '') {
      return true;
    }
    return false;
  }

  public static convertToCheck(val: any) {
    if (val) {
      return '√';
    }
    return '';
  }

  public static convertToBool(val: any) {
    if (val) {
      return true;
    }
    return false;
  }

  public static boolConvertToNumber(val: any) {
    if (val) {
      return 1;
    }
    return 0;
  }

  public static convertEnumToList(obj: any) {
    const list: any = [];
    if (obj) {
      for (const key in obj) {
        const val = obj[key];
        list.push({ value: Number.parseInt(key), label: val });
      }
    }
    return list;
  }
}
