import {
  Component,
  EventEmitter,
  Input,
  OnInit,
  Output,
  ViewEncapsulation
} from '@angular/core'
import { Router } from '@angular/router'
import { ServerType } from '@sasjs/utils/types/serverType'
import { EventService } from 'src/app/services/event.service'
import { HelperService } from 'src/app/services/helper.service'
import { SasService } from 'src/app/services/sas.service'
import { AbortDetails, InfoModal } from '../../models/InfoModal'

@Component({
  selector: 'app-info-modal',
  templateUrl: './info-modal.component.html',
  styleUrls: ['./info-modal.component.scss'],
  encapsulation: ViewEncapsulation.None,
  standalone: false
})
export class InfoModalComponent implements OnInit {
  @Output() onConfirmModalClick: EventEmitter<any> = new EventEmitter()
  @Input() data: InfoModal = new InfoModal()
  @Input() forceReload: boolean = false

  public modalEnabled: boolean = true

  public defaultData: InfoModal = {
    modalTitle: 'Abort Message',
    sasService: null,
    message: '',
    details: new AbortDetails()
  }

  constructor(
    private helperService: HelperService,
    private eventService: EventService,
    private sasService: SasService,
    private router: Router
  ) {}

  ngOnInit() {
    let newData: InfoModal = {
      ...this.defaultData,
      ...this.data
    }

    this.data = newData
  }

  /**
   * Wheter or not to show the `Open configurator button`
   * Button used for navigating to the `configuration` page
   * Only for SAS9
   * @param sasService backend service that caused this info modal to be shown
   * Decision is made based on that service path
   * @returns
   */
  showConfiguratorButton(sasService: string | null) {
    const sasjsConfig = this.sasService.getSasjsConfig()

    return (
      sasService?.includes('startupservice') &&
      sasjsConfig.serverType === ServerType.Sas9
    )
  }

  closeAbortModal() {
    this.onConfirmModalClick.emit()
  }

  /**
   * Only on SAS9, opening a backend configurator/deploy page
   */
  openConfigurator() {
    this.eventService.startupDataLoaded()
    this.router.navigateByUrl('/deploy')
    this.closeAbortModal()
  }

  downloadLog() {
    this.helperService.downloadTextFile(
      `${this.data.sasService}-LOG`,
      this.data.details?.LOG || 'Error parsing the log'
    )
  }

  openRequestsModal() {
    this.eventService.openRequestsModal()
  }

  reload() {
    location.reload()
  }
}
