/**
 * Both `start` and `end` are in seconds.
 */
export class TimeFragment {
  start: number | null;
  end: number | null;

  constructor(start: number, end: number) {
    this.start = start;
    this.end = end;
  }

  public static parse(fragment: string): TimeFragment {
    if (!fragment.startsWith("t=")) {
      return undefined;
    }
    const data = fragment.substring("t=".length);
    try {
      const [start, end] = data.split(",").map((str) => parseFloat(str));
      return new TimeFragment(start || null, end || null);
    } catch {
      return undefined;
    }
  }

  public toString(): string {
    return `t=${this.start || ""},${this.end || ""}`;
  }
}

export function formatDuration(duration: number): string {
  let result = "";

  const hours = Math.floor(duration / 3600);
  const minutes = Math.floor((duration % 3600) / 60);
  const seconds = Math.floor(duration - hours * 3600 - minutes * 60);

  result = "";
  if (hours > 0) {
    result += `${hours}h`;
  }
  result += `${minutes}m`.padStart(hours > 0 ? 3 : 2, "0");
  result += `${seconds}s`.padStart(3, "0");

  return result;
}
