/*
 * 时间相关工具类
 * EZOpenSDK
 *
 * Created by junecheng on 2024/5/22.
 * Copyright (c) 2024年 Ezviz. All rights reserved.
 */
export default class EZTimeUtil {
  /**
   * 将总秒数转换为时分秒
   * @param seconds
   * @returns
   */
  static formatSeconds(seconds: number) {
    let hour = Math.floor(seconds / 3600).toString()
    if (hour.length < 2) {
      hour = `0${hour}`
    }

    let minute = Math.floor((seconds % 3600) / 60).toString()
    if (minute.length < 2) {
      minute = `0${minute}`
    }

    let second = Math.floor(seconds % 60).toString()
    if (second.length < 2) {
      second = `0${second}`
    }

    return parseInt(hour) > 0 ? `${hour}:${minute}:${second}` : `${minute}:${second}`
  }

  /**
   * 传入两个Date，计算时长
   * @param date1 2024-08-21 10:53:40
   * @param date2 2024-08-21 10:54:58
   * @returns 01'18"
   */
  static formatTimeDifference(date1: Date, date2: Date): string {
    try {
      // Check if the inputs are valid Date objects
      if (!(date1 instanceof Date) || isNaN(date1.getTime())) {
        throw new Error("Invalid date1")
      }
      if (!(date2 instanceof Date) || isNaN(date2.getTime())) {
        throw new Error("Invalid date2")
      }

      // Calculate the difference in milliseconds
      const diffInMs = Math.abs(date1.getTime() - date2.getTime())

      // Convert milliseconds to minutes and seconds
      const diffInSeconds = Math.floor(diffInMs / 1000)
      const minutes = Math.floor(diffInSeconds / 60)
      const seconds = diffInSeconds % 60

      // Format the result as mm'ss''
      const formattedMinutes = String(minutes).padStart(2, '0')
      const formattedSeconds = String(seconds).padStart(2, '0')

      return `${formattedMinutes}'${formattedSeconds}''`
    } catch (error) {
      console.error(error)
      return "Invalid input"
    }
  }
}