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

@Component({
  selector: 'app-role',
  templateUrl: './role.component.html',
  styleUrls: ['./role.component.scss'],
  host: {
    class: 'content-container'
  },
  encapsulation: ViewEncapsulation.None,
  standalone: false
})
export class RoleComponent implements OnInit {
  public roles: Array<any> | undefined
  public roleSearch: string = ''
  public roleUri: string = ''
  public roleName: string = ''
  public roleDesc: string = ''
  public roleMembers: Array<any> | undefined
  public roleMembersCount: number | undefined
  public roleGroups: Array<any> | undefined
  public roleGroupsCount: number | undefined
  public paramPresent: boolean = false
  public paramURI: string = ''
  public loading: boolean = false

  constructor(
    private sasService: SasService,
    private helperService: HelperService,
    private router: Router,
    private location: Location,
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    globals.viewer.currentSelection = 'view/usernav/roles'
    if (this.route.snapshot.params['uri'] !== undefined) {
      this.paramPresent = true
      this.paramURI = this.route.snapshot.params['uri']
    }
    if (globals.usernav.roleList && !this.paramPresent) {
      this.roles = globals.usernav.roleList
      this.roleSearch = globals.usernav.roleSearch
    } else {
      if (globals.usernav.roleList === undefined) {
        this.loading = true
        this.sasService
          .request('usernav/userroles', null)
          .then((res: RequestWrapperResponse) => {
            this.loading = false
            this.roles = res.adapterResponse.roles
            globals.usernav.roleList = res.adapterResponse.roles
            if (this.paramPresent) {
              if (this.roles !== undefined) {
                let validRole = this.findRole(this.roles, this.paramURI)
                if (validRole !== false) {
                  this.loading = true
                  let data = { iwant: [{ roleid: this.paramURI }] }
                  this.sasService
                    .request('usernav/usermembersbyrole', data)
                    .then((res: RequestWrapperResponse) => {
                      this.loading = false
                      this.roleMembers = res.adapterResponse.sasmembers
                      this.roleMembersCount =
                        res.adapterResponse.sasmembers.length
                      this.roleGroups = res.adapterResponse.sasgroups
                      this.roleGroupsCount =
                        res.adapterResponse.sasgroups.length
                      this.roleUri = validRole.ROLEURI
                      this.roleName = validRole.ROLENAME
                      this.roleDesc = validRole.ROLEDESC
                    })
                }
              }
            }
          })
      } else {
        this.roles = globals.usernav.roleList
        this.roleSearch = globals.usernav.roleSearch
        this.sasService
          .request('usernav/userroles', null)
          .then((res: RequestWrapperResponse) => {
            this.roles = res.adapterResponse.roles
            globals.usernav.roleList = res.adapterResponse.roles

            if (this.paramPresent) {
              if (this.roles !== undefined) {
                let validRole = this.findRole(this.roles, this.paramURI)
                if (validRole !== false) {
                  this.loading = true
                  let data = { iwant: [{ roleid: this.paramURI }] }
                  this.sasService
                    .request('usernav/usermembersbyrole', data)
                    .then((res: RequestWrapperResponse) => {
                      this.loading = false
                      this.roleMembers = res.adapterResponse.sasmembers
                      this.roleMembersCount =
                        res.adapterResponse.sasmembers.length
                      this.roleGroups = res.adapterResponse.sasgroups
                      this.roleGroupsCount =
                        res.adapterResponse.sasgroups.length
                      this.roleUri = validRole.ROLEURI
                      this.roleName = validRole.ROLENAME
                      this.roleDesc = validRole.ROLEDESC
                    })
                }
              }
            }
          })
      }
    }
  }

  public roleListOnFilter() {
    this.helperService.libraryOnFilter(this.roles, this.roleSearch, 'ROLENAME')
    globals.usernav.roleSearch = this.roleSearch
  }

  public roleOnClick(role: any) {
    this.loading = true
    let url = this.router.url
    if (this.paramPresent) {
      this.location.replaceState(
        url.slice(0, url.lastIndexOf('/')) + '/' + encodeURI(role.ROLEURI)
      )
    } else {
      this.location.replaceState(url + '/' + encodeURI(role.ROLEURI))
    }

    let data = { iwant: [{ roleid: role.ROLEURI }] }
    this.sasService
      .request('usernav/usermembersbyrole', data)
      .then((res: RequestWrapperResponse) => {
        this.loading = false
        this.roleMembers = res.adapterResponse.sasmembers
        this.roleMembersCount = res.adapterResponse.sasmembers.length
        this.roleGroups = res.adapterResponse.sasgroups
        this.roleGroupsCount = res.adapterResponse.sasgroups.length
        this.roleUri = role.ROLEURI
        this.roleName = role.ROLENAME
        this.roleDesc = role.ROLEDESC
      })
  }

  public findRole(list: Array<any>, role: any): any {
    let result = false
    list.forEach((element) => {
      if (element.ROLEURI === role) {
        result = element
      }
    })
    return result
  }
}
