import { Component, OnInit, ViewEncapsulation } from '@angular/core'

/**
 * Goal of this component is to recieve array of strings where every element is one state
 * and to append them in html while showing the loading spinner.
 * Even if states change quickly, this component will keep every state for at least miliseconds
 * that are defines in `minDelay` variable.
 */

@Component({
  selector: 'app-upload-stater',
  templateUrl: './upload-stater.component.html',
  styleUrls: ['./upload-stater.component.scss'],
  encapsulation: ViewEncapsulation.None,
  standalone: false
})
export class UploadStaterComponent implements OnInit {
  public statesList: string[] = [] //States appended to be displayed
  public processedStates: string[] = [] //States that has been displayed and processed

  /**
   * Stater config
   */
  public staterInProgress: boolean = false
  private stateInterval: any
  private minDelay: number = 1000

  constructor() {}

  ngOnInit(): void {}

  public appendState(state: string) {
    if (state === '{finish}') {
      /**
       * Stop the stater progress
       */
      this.staterInProgress = false
      clearInterval(this.stateInterval)

      return
    }

    this.statesList.push(state)
    this.processedStates.push(state)

    // We are disabling delaying functionality for now
    // if (!this.staterInProgress) {
    //   this.startStater()
    // }
  }

  public replaceLastState(state: string) {
    if (this.statesList.length > 0) {
      this.statesList.pop()
      this.statesList.push(state)
    } else {
      this.processedStates[this.processedStates.length - 1] = state
    }
  }

  public clearStates() {
    this.processedStates = []
  }

  private startStater() {
    this.staterInProgress = true

    //First run
    if (this.statesList.length > 0) {
      this.processedStates.push(this.statesList.shift() || '')
    }

    this.stateInterval = setInterval(() => {
      if (this.statesList.length > 0) {
        this.processedStates.push(this.statesList.shift() || '')
      }
    }, this.minDelay)
  }
}
