import { Component, OnInit, ViewEncapsulation } from '@angular/core'
import { SasService } from '../services/sas.service'
import { SASjsConfig } from '@sasjs/adapter'
import { Router } from '@angular/router'
import { LoggerService } from '../services/logger.service'
import { ServerType } from '@sasjs/utils/types/serverType'
import { AppStoreService } from '../services/app-store.service'
import { DcAdapterSettings } from '../models/DcAdapterSettings'

@Component({
  selector: 'app-deploy',
  templateUrl: './deploy.component.html',
  styleUrls: ['./deploy.component.scss'],
  host: {
    class: 'content-container'
  },
  encapsulation: ViewEncapsulation.None,
  standalone: false
})
export class DeployComponent implements OnInit {
  public step: number = 0
  public adminGroups: any = []

  public client_id: string = ''
  public client_secret: string = ''
  public appLoc: string = ''
  public dcPath: string = ''
  public selectedAdminGroup: string = ''

  public autodeploy: boolean = true
  public jsonFile: any = null

  public sasJs: any
  public sasJsConfig: SASjsConfig = new SASjsConfig()

  public dcAdapterSettings: DcAdapterSettings | undefined

  ServerType = ServerType

  constructor(
    private appStoreService: AppStoreService,
    private sasService: SasService,
    private loggerService: LoggerService,
    private router: Router
  ) {
    this.dcAdapterSettings = this.appStoreService.getDcAdapterSettings()

    if (this.router.url.includes('manualdeploy')) {
      this.autodeploy = false
    }

    this.sasJs = this.sasService.getSasjsInstance()
    this.sasJsConfig = this.sasService.getSasjsConfig()
    this.appLoc = this.dcAdapterSettings?.appLoc || ''
    this.client_id = localStorage.getItem('deploy_client_id') || ''
    this.client_secret = localStorage.getItem('deploy_secret_key') || ''
    this.dcPath = localStorage.getItem('deploy_dc_loc') || ''
  }

  ngOnInit() {
    this.setDeployDefaults()
  }

  /**
   * Setting default values used for deploy request
   */
  public setDeployDefaults() {
    this.dcPath = this.dcAdapterSettings?.dcPath || ''
    this.selectedAdminGroup = this.dcAdapterSettings?.adminGroup || ''
    if (!this.selectedAdminGroup) {
      this.selectedAdminGroup = 'SASAdministrators'
    }
  }

  /**
   * Accepting terms of service shows next screen
   */
  public termsAgreeChange() {
    if (!this.autodeploy) {
      this.getAdminGroups()
    }

    this.step++
  }

  /**
   * Fetches admin groups from VIYA to be selected for a backend deploy
   */
  public getAdminGroups() {
    fetch(
      this.sasJsConfig.serverUrl + '/identities/groups?sortBy=name&limit=5000',
      {
        headers: {
          Accept: 'application/json'
        }
      }
    )
      .then((res: any) => {
        return res.text()
      })
      .then((res: any) => {
        let jsonRes

        try {
          jsonRes = JSON.parse(res)
        } catch (err: any) {
          console.error(err)
        }

        if (jsonRes) {
          this.adminGroups = jsonRes.items
          this.selectedAdminGroup = this.adminGroups[0].id
        }
      })
  }

  public onNavigateToHome() {
    window.open(location.href.split('#')[0], '_blank')
  }
}
