import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { User, Spec, Character } from '../../../../../../backend/Types/Types';
import { getClassColor } from '../../../../../../backend/Types/PlayerSpecs';
import { _Tiers } from '../../../../../../backend/Types/Items';
import { _Rank } from '../../../../../../backend/Types/Types';
import { NbToastrService } from '@nebular/theme';
import { hash, IApiService } from '../../services/ApiService/ApiService';

@Component({
  selector: 'user-component',
  templateUrl: './user.component.html',
})
export class FrontcraftUserComponent implements OnInit{

  newPw
  newPwConfirm

  ranks = _Rank
  myProfile = false
  manageUser
  user:User = {
    rank: 'Guest',
    username: 'Guest',
    pwhash: ""
  }
  characters : (Character & Spec)[] = []

  constructor(
    private route: ActivatedRoute,
    private api : IApiService,
    private toastr: NbToastrService
  ){}

  async ngOnInit(){
    const param = this.route.snapshot.paramMap.get('name');
    const usr = await this.api.get('UserManager').getUser(param)

    if(!usr) return
    this.user = usr

    this.manageUser = this.api.get('manageUser')
    this.myProfile = this.api.getCurrentUser().username === this.user.username
    
    const characters = await this.api.get('CharacterManager').getCharactersOfUser(this.user.username)
    characters.forEach(async c => {
      const tokens = await this.api.get('ItemManager').getTokens(c, _Tiers, true)
      c['tokens'] = tokens
      c['color'] = getClassColor(c.class)
    })
    this.characters = characters
  }

  async onSelectRank(){
    const manage = this.api.get('manageUser')
    if(!manage) return
    await manage.changeRank(this.user, this.user.rank)
    this.toastr.success("Rank changed to "+this.user.rank, "Update success")
  }

  async submitPasswordChange(){
    const pw = await hash(this.newPw)
    this.newPw = null
    this.newPwConfirm = null

    const manage = this.api.get('manageUser')
    if(!manage){
      await this.api.get('UserManager').changePassword(this.api.getAuth().token.value, pw)
    }else{
      await manage.adminChangePassword(this.user, pw)
    }
  }
}