/* eslint-disable @typescript-eslint/unified-signatures */
import { HttpStep, IHttpStep } from '../../HttpStep.js'

export const SubstringStepKind = 'HttpAction#Substring'

/**
 * Returns the part of the string from the start index up to and excluding the end index, or to the end
 * of the string if no end index is supplied.
 * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring
 */
export interface ISubstringStep extends IHttpStep {
  kind: typeof SubstringStepKind

  /**
   * The index of the first character to include in the returned substring.
   */
  start?: number

  /**
   * The index of the first character to exclude from the returned substring.
   */
  end?: number
}

/**
 * Returns the part of the string from the start index up to and excluding the end index, or to the end
 * of the string if no end index is supplied.
 * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring
 */
export class SubstringStep extends HttpStep {
  override kind = SubstringStepKind

  /**
   * The index of the first character to include in the returned substring.
   */
  start?: number

  /**
   * The index of the first character to exclude from the returned substring.
   */
  end?: number

  constructor(start: number, end?: number)

  constructor(init: ISubstringStep)

  constructor()

  constructor(startOrInit?: number | ISubstringStep, end?: number) {
    super()
    if (typeof startOrInit === 'object') {
      const typed = startOrInit as ISubstringStep
      this.new(typed)
    } else if (typeof startOrInit === 'number') {
      this.new({
        kind: SubstringStepKind,
        start: startOrInit,
        end,
        enabled: true,
      })
    }
  }

  override new(init: ISubstringStep): void {
    super.new(init)
    this.kind = SubstringStepKind
    if (typeof init.start === 'number') {
      this.start = init.start
    } else {
      this.start = undefined
    }
    if (typeof init.end === 'number') {
      this.end = init.end
    } else {
      this.end = undefined
    }
  }

  checkValidity(): boolean {
    return typeof this.start === 'number'
  }

  override toJSON(): ISubstringStep {
    const result: ISubstringStep = {
      ...super.toJSON(),
      kind: SubstringStepKind,
    }
    if (typeof this.start === 'number') {
      result.start = this.start
    }
    if (typeof this.end === 'number') {
      result.end = this.end
    }
    return result
  }
}
