// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
const PATH = require('path');
const {
  AnalysisTypes,
  WebVttHelper,
  CommonUtils,
} = require('core-lib');
const BaseStateIndexer = require('../shared/baseStateIndexer');

const SUB_CATEGORY = AnalysisTypes.Transcribe;

class StateIndexTranscribeResults extends BaseStateIndexer {
  constructor(stateData) {
    super(stateData, SUB_CATEGORY);
    this.$sanitizedVtt = undefined;
  }

  get [Symbol.toStringTag]() {
    return 'StateIndexTranscribeResults';
  }

  get dataKey() {
    return this.stateData.data[SUB_CATEGORY].vtt;
  }

  get sanitizedVtt() {
    return this.$sanitizedVtt;
  }

  set sanitizedVtt(val) {
    this.$sanitizedVtt = val;
  }

  async process() {
    const response = await super.process();

    await this.workaroundInvalidVttTimestamps();

    return response;
  }

  async workaroundInvalidVttTimestamps() {
    /* workaround invalid timestamp WebVTT file generated by Amazon Transcribe */
    if (this.sanitizedVtt !== undefined) {
      const bucket = this.stateData.input.destination.bucket;
      const key = this.dataKey;
      const parsed = PATH.parse(key);

      await CommonUtils.uploadFile(
        bucket,
        parsed.dir,
        parsed.base,
        this.sanitizedVtt
      ).catch(() =>
        undefined);
    }
  }

  parseDataset(datasets) {
    if (!datasets) {
      return undefined;
    }

    const vtt = WebVttHelper.parse(datasets, {
      autoCorrect: true,
      stripLeadingDashes: true,
    });

    if (((vtt || {}).cues || []).length === 0) {
      return undefined;
    }

    /* store the modified vtt to upload it later */
    this.sanitizedVtt = WebVttHelper.compile(vtt);

    return WebVttHelper.cuesToMetadata(vtt.cues);
  }
}

module.exports = StateIndexTranscribeResults;
