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

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.scss'],
  host: {
    class: 'content-container'
  },
  encapsulation: ViewEncapsulation.None,
  standalone: false
})
export class UserComponent implements OnInit {
  public users: Array<any> | undefined
  public loading: boolean = false
  public userSearch: string = ''
  public userData: Array<any> | undefined
  public userInfo: any | undefined
  public userEmails: Array<any> | undefined
  public userEmailsCount: number | undefined
  public userGroups: Array<any> | undefined
  public userGroupsCount: number | undefined
  public userRoles: Array<any> | undefined
  public userRolesCount: number | undefined
  public userLogins: Array<any> | undefined
  public userLoginsCount: number | undefined
  public paramPresent: boolean = false
  public paramName: string = ''
  public sasjsConfig: SASjsConfig = new SASjsConfig()
  public isViya: boolean = false
  public serverType: string = ''

  ServerType = ServerType

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

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

  ngOnInit() {
    globals.viewer.currentSelection = 'view/usernav/users'
    if (this.route.snapshot.params['uri'] !== undefined) {
      this.paramPresent = true
      this.paramName = this.route.snapshot.params['uri']
    }
    if (globals.usernav.userList && !this.paramPresent) {
      this.users = globals.usernav.userList
      this.userSearch = globals.usernav.userSearch
    } else {
      if (globals.usernav.userList === undefined) {
        this.loading = true
        if (this.isViya) {
          fetch(this.sasjsConfig.serverUrl + '/identities/users?limit=2000', {
            headers: {
              Accept: 'application/json'
            }
          })
            .then((res: any) => {
              return res.text()
            })
            .then((res: any) => {
              let jsonRes = JSON.parse(res)
              let users = jsonRes.items.map((user: any) => {
                return {
                  NAME: user.name,
                  URI: user.id,
                  PROVIDER: user.providerId
                }
              })
              this.loading = false
              this.users = users
              globals.usernav.userList = users
            })
        } else {
          this.sasService
            .request('usernav/usermembers', null)
            .then((res: RequestWrapperResponse) => {
              this.loading = false
              this.users = res.adapterResponse.users
              globals.usernav.userList = res.adapterResponse.users
            })
        }
      } else {
        this.users = globals.usernav.userList
        this.userSearch = globals.usernav.userSearch
      }
      if (this.paramPresent) {
        this.loading = true

        if (this.isViya) {
          let uri = this.route.snapshot.params['uri']
          fetch(
            this.sasjsConfig.serverUrl +
              '/identities/users/' +
              uri +
              '/memberships?limit=2000',
            {
              headers: {
                Accept: 'application/json'
              }
            }
          )
            .then((res: any) => {
              return res.text()
            })
            .then((res: any) => {
              let jsonRes = JSON.parse(res)
              this.userData = jsonRes
              this.loading = false
              let groups = jsonRes.items.map((group: any) => {
                return {
                  GROUPNAME: group.name,
                  URI: group.id
                }
              })
              this.userGroups = groups
              this.userGroupsCount = groups.length

              if (this.users) {
                this.userInfo = this.users.find((userAr) => userAr.URI === uri)
              }
            })
        } else {
          const uri = this.route.snapshot.params['uri']
          let data = { iwant: [{ uri }] }

          this.sasService
            .request('usernav/usergroupsbymember', data)
            .then((res: RequestWrapperResponse) => {
              this.loading = false

              switch (this.serverType) {
                case ServerType.Sas9: {
                  this.userInfo = res.adapterResponse.info[0]
                  this.userEmails = res.adapterResponse.emails
                  this.userEmailsCount = res.adapterResponse.emails.length
                  this.userRoles = res.adapterResponse.roles
                  this.userRolesCount = res.adapterResponse.roles.length
                  this.userLogins = res.adapterResponse.logins
                  this.userLoginsCount = res.adapterResponse.logins.length

                  break
                }
                case ServerType.Sasjs: {
                  if (this.users) {
                    this.userInfo = this.users.find(
                      (userAr) => userAr.URI === uri
                    )
                  } else {
                    const group = res.adapterResponse.groups[0]

                    this.userInfo = {
                      URI: group.ID,
                      NAME: group.NAME,
                      DISPLAYNAME: group.NAME
                    }
                  }

                  break
                }
              }

              this.userData = res.adapterResponse
              this.userGroups = res.adapterResponse.groups
              this.userGroupsCount = res.adapterResponse.groups.length
            })
        }
      }
    }
  }

  public userListOnFilter() {
    this.helperService.libraryOnFilter(this.users, this.userSearch, 'NAME')
    globals.usernav.userSearch = this.userSearch
  }

  public userOnClick(user: any) {
    this.loading = true
    let url = this.router.url
    if (this.paramPresent) {
      this.location.replaceState(
        url.slice(0, url.lastIndexOf('/')) + '/' + encodeURI(user.URI)
      )
    } else {
      this.location.replaceState(url + '/' + encodeURI(user.URI))
    }
    if (this.isViya) {
      fetch(
        this.sasjsConfig.serverUrl +
          '/identities/users/' +
          user.URI +
          '/memberships?limit=2000',
        {
          headers: {
            Accept: 'application/json'
          }
        }
      )
        .then((res: any) => {
          return res.text()
        })
        .then((res: any) => {
          let jsonRes = JSON.parse(res)

          this.userData = jsonRes
          this.loading = false

          let groups = jsonRes.items.map((group: any) => {
            return {
              GROUPNAME: group.name,
              URI: group.id
            }
          })

          this.userGroups = groups
          this.userGroupsCount = groups.length

          if (this.users) {
            this.userInfo = this.users.find((userAr) => userAr.URI === user.URI)
          }
        })
    } else {
      let data = { iwant: [{ uri: user.URI }] }
      this.sasService
        .request('usernav/usergroupsbymember', data)
        .then((res: RequestWrapperResponse) => {
          this.loading = false

          switch (this.serverType) {
            case ServerType.Sas9: {
              this.userInfo = res.adapterResponse.info[0]
              this.userEmails = res.adapterResponse.emails
              this.userEmailsCount = res.adapterResponse.emails.length
              this.userRoles = res.adapterResponse.roles
              this.userRolesCount = res.adapterResponse.roles.length
              this.userLogins = res.adapterResponse.logins
              this.userLoginsCount = res.adapterResponse.logins.length

              break
            }
            case ServerType.Sasjs: {
              if (this.users) {
                this.userInfo = this.users.find(
                  (userAr) => userAr.URI === user.URI
                )
              } else {
                const group = res.adapterResponse.groups[0]

                this.userInfo = {
                  URI: group.ID,
                  NAME: group.NAME,
                  DISPLAYNAME: group.NAME
                }
              }

              break
            }
          }

          this.userData = res.adapterResponse
          this.userGroups = res.adapterResponse.groups
          this.userGroupsCount = res.adapterResponse.groups.length
        })
    }
  }

  public getRoleURI(role: any) {
    return role.split('OMSOBJ:IdentityGroup')[1].slice(1)
  }
}
