import { Component, OnInit } from '@angular/core';
import { Route, Router } from '@angular/router';
import { AlertController } from '@ionic/angular';
import * as Parse from 'parse';
@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {

  username:string = ""
  password:string = ""

  constructor(private router:Router,private alertController:AlertController) { }

  ngOnInit() {
  }

  async login(){
    let user

    try {
      user = await Parse.User.logIn(this.username,this.password)
    } catch (error:any) {
      let message:string = ""
      if(error?.message.indexOf("is required")>-1){
        message = "账号不能为空"
      }
      if(error?.message.indexOf("Invalid username")>-1){
        message = "账号或密码错误"
      }
      this.presentAlert({
        header:"登录失败",
        subHeader:"状态码:" + error.code,
        message:message || error.message,
      })
      
    }

    
    console.log(user)
    if(user?.id){
      this.router.navigateByUrl("/tabs/tab3")
    }
  }
  async register(){
    let user = new Parse.User()
    user.set("username",this.username)
    user.set("password",this.password)
    try {
      let result = await user.signUp();
      console.log(result)
      if(result?.id){
        this.router.navigateByUrl("/tabs/tab3")
      }
      // Hooray! Let them use the app now.
    } catch (error:any) {
      // Show the error message somewhere and let the user try again.
      alert("Error: " + error.code + " " + error.message);
      let message:string = ""
      if(error?.message.indexOf("already exist")>-1){
        message = "该账号已存在请修改后重试"
      }
      if(error?.message.indexOf("empty")>-1){
        message = "账号不能为空请输入后重试"
      }
      this.presentAlert({
        header:"注册失败",
        subHeader:"状态码:" + error.code,
        message:message || error.message,
      })
    }

  }

  async presentAlert(options:{header:string,subHeader:string,message:string}) {
    const alert = await this.alertController.create({
      header: options?.header,
      subHeader: options?.subHeader,
      message: options?.message,
      buttons: ['好的'],
    });

    await alert.present();
  }

  back(){
    let path = "/tabs/tab3"
    path = localStorage.getItem("LOGIN_REDIRECT_URL") || path;
    this.router.navigateByUrl(path)
  }

}
