import { Component, OnInit } from '@angular/core';
import { ApiService as ApiService, hash } from '../../services/login-api';
import { Router } from '@angular/router';
import { _Rank, _Class, Class, User, _Race  } from '../../../../../../backend/Types/Types'
import { specs  } from '../../../../../../backend/Types/PlayerSpecs'
import { race } from 'rxjs';


@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 = _Rank
  classes = _Class
  races  = _Race
  selectedClass : Class = "Warrior"
  selectedSpec = specs[this.selectedClass][0]
  specs = specs[this.selectedClass]
  showApplication = false

  constructor(
    private router : Router,  
    private api : ApiService
  ){}

  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
      })
    }catch(e){
      alert("Error creating character"+e)
      return
    }
  }
}