import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { _Rank, _Class, Class, User, _Race  } from '../../../../../../backend/Types/Types'
import { specs  } from '../../../../../../backend/Types/PlayerSpecs'
import { hash, IApiService } from '../../services/ApiService/ApiService';


@Component({
  selector: 'register',
  templateUrl: './register.component.html',
})
export class RegisterComponent implements OnInit{

  user = {
    rank: "Guest"
  } as User

  character: any = {
    class : "Warrior",
    spec : "Arms",
    race: "Night Elf"
  }

  ranks = ["Trial"] //remove admin, gm, officer
  classes = _Class
  races  = _Race
  selectedClass : Class = "Warrior"
  specs = specs[this.selectedClass]
  selectedSpec = specs[this.selectedClass][0]
  showApplication = false
  submitted = false

  constructor(
    private router : Router,
    private route : ActivatedRoute,
    private api : IApiService
  ){}

  ngOnInit(){
    this.api.checkLogin().then(loggedin => {
      if(loggedin){
        this.router.navigateByUrl("/")
      }
    })
  }

  onSelectClass(){
    this.specs = specs[this.character.class]
    setTimeout(() => {
      this.character.spec = this.specs[0]
    }, 25)
  }

  onSelectSpec(){
  }

  onSelectRace(){}

  async onSubmit(){
    const pw = this.user.pwhash
    this.user.pwhash = await hash(this.user.pwhash)
    const user = this.user
    this.user = {} as User
    const char = this.character
    this.character = {}

    try{
      const usr = await this.api.get('UserManager').createUser(user)
    }catch(e){
      alert("Error creating user"+e)
      return
    }

    try{
      await this.api.login(user.username, pw)

      const characterManager = this.api.get('CharacterManager')

      const specid = await characterManager.getSpecId(char['class'], char['spec'])
      await characterManager.createCharacter(this.api.getAuth().token.value, {
        charactername: char.name,
        specid: specid,
        userid: this.api.getAuth().user.id!,
        race: char.race
      })

      this.route.queryParamMap.subscribe(params => {
        this.router.navigate([params.get('redirect')])        
      })

    }catch(e){
      alert("Error creating character"+e)
      return
    }
  }
}