/**
 * Copyright 2015 CANAL+ Group
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import bufferSourceToUint8 from "../../../../utils/buffer_source_to_uint8";
import { utf8ToStr } from "../../../../utils/string_parsing";
import parseTtml from "../parse_ttml";
import {
  applyDefaultTTMLStyle,
  shouldApplyDefaultTTMLStyle,
} from "./apply_default_ttml_paragraph_style";
import type { ITTMLHTMLCue } from "./parse_cue";
import parseCue from "./parse_cue";

/**
 * Create array of objects which should represent the given TTML text track.
 * These objects have the following structure
 *   - start {Number}: start time, in seconds, at which the cue should
 *     be displayed
 *   - end {Number}: end time, in seconds, at which the cue should
 *     be displayed
 *   - element {HTMLElement}: <div> element representing the cue, with the
 *     right style. This div should then be appended to an element having
 *     the exact size of the wanted region the text track provide cues for.
 *
 * TODO TTML parsing is still pretty heavy on the CPU.
 * Optimizations have been done, principally to avoid using too much XML APIs,
 * but we can still do better.
 * @param {string|BufferSource} input
 * @param {Object} _context
 * @param {number} timeOffset
 */
export default function parseTTMLToDiv(
  input: string | BufferSource,
  _context: unknown,
  timeOffset: number,
): ITTMLHTMLCue[] {
  let str: string;
  if (typeof input !== "string") {
    // Assume UTF-8
    // TODO: detection?
    str = utf8ToStr(bufferSourceToUint8(input));
  } else {
    str = input;
  }
  const parsedCues = parseTtml(str, timeOffset);
  const cues: ITTMLHTMLCue[] = [];
  for (const parsedCue of parsedCues) {
    const { paragraphStyle } = parsedCue;
    if (shouldApplyDefaultTTMLStyle(paragraphStyle)) {
      applyDefaultTTMLStyle(paragraphStyle);
    }
    const cue = parseCue(parsedCue);
    if (cue !== null) {
      cues.push(cue);
    }
  }
  return cues;
}
