import { Location } from '@angular/common'
import {
  Component,
  EventEmitter,
  Input,
  OnInit,
  Output,
  ViewEncapsulation
} from '@angular/core'
import SASjs, { SASjsConfig } from '@sasjs/adapter'
import { ServerType } from '@sasjs/utils/types/serverType'
import { DcAdapterSettings } from 'src/app/models/DcAdapterSettings'
import { RequestWrapperResponse } from 'src/app/models/request-wrapper/RequestWrapperResponse'
import { SASGroup } from 'src/app/models/sas/public-getgroups.model'
import { SASjsApiServerInfo } from 'src/app/models/sasjs-api/SASjsApiServerInfo.model'
import { SasService } from 'src/app/services/sas.service'
import { SasjsService } from 'src/app/services/sasjs.service'

@Component({
  selector: 'app-sasjs-configurator',
  templateUrl: './sasjs-configurator.component.html',
  styleUrls: ['./sasjs-configurator.component.scss'],
  encapsulation: ViewEncapsulation.None,
  standalone: false
})
export class SasjsConfiguratorComponent implements OnInit {
  @Input() sasJs!: SASjs
  @Input() sasJsConfig: SASjsConfig = new SASjsConfig()
  @Input() dcAdapterSettings: DcAdapterSettings | undefined

  @Output() onNavigateToHome: EventEmitter<any> = new EventEmitter<any>()

  dcDirectory: string = ''
  dcAdminGroup: string = 'DCDEFAULT'

  METAPERSON: string = 'n/a'
  METAUSER: string = 'n/a'
  SYSUSERID: string = 'n/a'
  SYSHOSTNAME: string = 'n/a'
  SYSVLONG: string = 'n/a'

  dcAdminGroupList: SASGroup[] = []

  loading: boolean = false
  showLogout: boolean = false

  tmpDirectories = {
    linux: '/tmp/DataController',
    windows: 'C:\\DataController'
  }

  constructor(
    private sasService: SasService,
    private sasjsService: SasjsService,
    private location: Location
  ) {}

  ngOnInit(): void {
    this.getUserGroups()
    this.getServerInfo()
  }

  /**
   * Fethes the sasjs server instance info
   */
  getServerInfo() {
    this.sasjsService
      .getServerInfo()
      .subscribe((serverInfo: SASjsApiServerInfo) => {
        if (serverInfo.mode !== 'desktop') this.showLogout = true
      })
  }

  /**
   * Fetches user groups from the `usernav/usergroupsbymember` service
   */
  getUserGroups() {
    this.loading = true

    this.sasService.request('usernav/usergroupsbymember', null).then(
      (res: RequestWrapperResponse) => {
        this.METAPERSON = res.adapterResponse.MF_GETUSER
        this.SYSUSERID = res.adapterResponse.SYSUSERID
        this.SYSHOSTNAME = res.adapterResponse.SYSHOSTNAME
        this.SYSVLONG = res.adapterResponse.SYSVLONG

        /*
          We would like to present a default DCPATH (deployment path) to the
          user who is installing Data Controller.  This path should be
          appropriate to the server type, ie windows or linux.
          We can use the SYSSCPL variable from the service response above, and
          derive the OS based on the first letter.

          The list of values is available here:

          https://documentation.sas.com/doc/en/pgmsascdc/9.4_3.5/mcrolref/n0e7s8lf147kazn17u45trpwb6sw.htm

        */
        this.dcDirectory =
          this.tmpDirectories[
            ['L', 'H', 'A', 'S'].includes(
              res.adapterResponse.SYSSCPL.substring(0, 1)
            )
              ? 'linux'
              : 'windows'
          ]

        this.dcAdminGroupList = res.adapterResponse.groups
        this.dcAdminGroup = this.dcAdminGroupList[0].GROUPNAME

        this.loading = false
      },
      (err: any) => {
        this.loading = false
      }
    )
  }

  /**
   * Creating database
   */
  makeData() {
    // const _debug = "&_debug=131"; //debug on
    const _debug = ' ' //debug off

    let executor = this.sasService.getExecutionPath()
    const root = this.sasJsConfig.appLoc
    let serverUrl = this.sasJsConfig.serverUrl
    let dcDirectory = this.dcDirectory

    if (this.sasJsConfig.serverType === ServerType.Sasjs) {
      this.sasService.sasjsMakedataChecking().then((success: boolean) => {
        if (!!success) {
          this.location.replaceState('/')
          location.reload()
        }
      })
    } else if (this.sasJsConfig.serverType === ServerType.Sas9) {
      serverUrl = ''
      executor = window.location.origin + executor + '/'
      dcDirectory = encodeURIComponent(this.dcDirectory)
    }

    const url = `${
      serverUrl ? serverUrl : ''
    }${executor}?_program=${root}/services/admin/makedata&admin=${
      this.dcAdminGroup
    }&path=${dcDirectory}${_debug}`

    window.open(url, '_blank')
  }

  logout() {
    this.sasService.logout()
  }
}
