import { Location } from '@angular/common'
import { Component, OnInit, ViewEncapsulation } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { SASjsConfig } from '@sasjs/adapter'
import { ServerType } from '@sasjs/utils/types/serverType'
import { HelperService } from '../services/helper.service'
import { SasService } from '../services/sas.service'
import { globals } from '../_globals'
import { RequestWrapperResponse } from '../models/request-wrapper/RequestWrapperResponse'

@Component({
  selector: 'app-group',
  templateUrl: './group.component.html',
  styleUrls: ['./group.component.scss'],
  host: {
    class: 'content-container'
  },
  encapsulation: ViewEncapsulation.None,
  standalone: false
})
export class GroupComponent implements OnInit {
  public groups: Array<any> | undefined
  public groupSearch: string = ''
  public groupMembers: Array<any> | undefined
  public groupMemberCount: number | undefined
  public paramPresent: boolean = false
  public paramURI: string = ''
  public groupUri: string = ''
  public groupName: string = ''
  public groupDesc: string = ''
  public sasjsConfig: SASjsConfig = new SASjsConfig()
  public isViya: boolean = false
  public loading: boolean = false
  public serverType: string

  ServerType = ServerType

  constructor(
    private sasService: SasService,
    private helperService: HelperService,
    private router: Router,
    private location: Location,
    private route: ActivatedRoute
  ) {
    this.sasjsConfig = this.sasService.getSasjsConfig()
    this.serverType = this.sasService.getServerType()

    if (this.sasjsConfig.serverType === 'SASVIYA') {
      this.isViya = true
    }
  }

  ngOnInit() {
    globals.viewer.currentSelection = 'view/usernav/groups'
    if (this.route.snapshot.params['uri'] !== undefined) {
      this.paramPresent = true
      this.paramURI = this.route.snapshot.params['uri']
    }
    if (globals.usernav.groupList && !this.paramPresent) {
      this.groups = globals.usernav.groupList
      this.groupSearch = globals.usernav.groupSearch
    } else {
      if (globals.usernav.groupList === undefined) {
        this.loading = true
        if (this.isViya) {
          fetch(this.sasjsConfig.serverUrl + '/identities/groups?limit=2000', {
            headers: {
              Accept: 'application/json'
            }
          })
            .then((res: any) => {
              return res.text()
            })
            .then((res: any) => {
              let jsonRes = JSON.parse(res)
              let groups = jsonRes.items.map((group: any) => {
                return {
                  GROUPURI: group.id,
                  GROUPNAME: group.name,
                  GROUPDESC: group.description
                }
              })
              this.loading = false
              this.groups = groups
              globals.usernav.groupList = groups
            })
        } else {
          this.sasService
            .request('public/getgroups', null)
            .then((res: RequestWrapperResponse) => {
              this.loading = false
              this.groups = res.adapterResponse.groups
              globals.usernav.groupList = res.adapterResponse.groups
            })
        }
      } else {
        this.groups = globals.usernav.groupList
        this.groupSearch = globals.usernav.groupSearch
      }
      if (this.paramPresent) {
        this.loading = true

        if (this.isViya) {
          fetch(
            this.sasjsConfig.serverUrl +
              '/identities/groups/' +
              this.paramURI +
              '/members?limit=2000',
            {
              headers: {
                Accept: 'application/json'
              }
            }
          )
            .then((res: any) => {
              return res.text()
            })
            .then((res: any) => {
              let jsonRes = JSON.parse(res)
              this.loading = false
              let groupMembers = jsonRes.items.map((member: any) => {
                return {
                  MEMBERNAME: member.name,
                  MEMBERID: member.id
                }
              })
              this.groupMembers = groupMembers
              this.groupMemberCount = groupMembers.length
              this.groupUri = this.paramURI
              this.groupName = this.paramURI
            })
        } else {
          let data = { iwant: [{ groupid: this.paramURI }] }
          this.sasService
            .request('usernav/usermembersbygroup', data)
            .then((res: RequestWrapperResponse) => {
              this.groupMembers = res.adapterResponse.sasmembers
              this.groupMemberCount = res.adapterResponse.sasmembers.length
              if (res.adapterResponse.sasmembers[0] !== undefined) {
                this.loading = false
                this.groupUri =
                  res.adapterResponse.sasmembers[0].URIMEM || this.paramURI
                this.groupName = res.adapterResponse.sasmembers[0].GROUPNAME
                this.groupDesc = res.adapterResponse.sasmembers[0].GROUPDESC

                if (!this.groupName) {
                  this.groupName = this.paramURI
                }
              }
            })
        }
      }
    }
  }

  public groupListOnFilter() {
    this.helperService.libraryOnFilter(
      this.groups,
      this.groupSearch,
      'GROUPNAME'
    )
    globals.usernav.groupSearch = this.groupSearch
  }

  public groupOnClick(group: any) {
    this.loading = true
    let url = this.router.url

    if (this.paramPresent) {
      this.location.replaceState(
        url.slice(0, url.lastIndexOf('/')) + '/' + encodeURI(group.GROUPURI)
      )
    } else {
      this.location.replaceState(url + '/' + encodeURI(group.GROUPURI))
    }
    if (this.isViya) {
      fetch(
        this.sasjsConfig.serverUrl +
          '/identities/groups/' +
          group.GROUPURI +
          '/members?limit=2000',
        {
          headers: {
            Accept: 'application/json'
          }
        }
      )
        .then((res: any) => {
          return res.text()
        })
        .then((res: any) => {
          let jsonRes = JSON.parse(res)
          this.loading = false
          this.groupUri = group.GROUPURI
          this.groupName = group.GROUPNAME
          this.groupDesc = group.GROUPDESC
          let groupMembers = jsonRes.items.map((member: any) => {
            return {
              MEMBERNAME: member.name,
              MEMBERID: member.id
            }
          })
          this.groupMembers = groupMembers
          this.groupMemberCount = groupMembers.length
        })
    } else {
      let data = { iwant: [{ groupid: group.GROUPURI }] }

      this.sasService
        .request('usernav/usermembersbygroup', data)
        .then((res: RequestWrapperResponse) => {
          this.loading = false
          this.groupUri = group.GROUPURI
          this.groupName = group.GROUPNAME
          this.groupDesc = group.GROUPDESC
          this.groupMembers = res.adapterResponse.sasmembers
          this.groupMemberCount = res.adapterResponse.sasmembers.length
        })
    }
  }
}
