import { Component, OnInit } from '@angular/core';
import {
  FormControl, FormGroup, FormBuilder, FormGroupDirective, NgForm, Validators,
} from '@angular/forms';
import { AuthService } from 'src/app/service/auth.service';
import { CookieService } from 'src/app/service/cookie.service';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  loginMethod = 'username';

  loading = false;

  loginFormGroup:FormGroup;

  step = 1;

  usernameFormControl;

  passwordFormControl;

  returnUrl:string;

  constructor(
    private authService:AuthService,
    private formBuilder:FormBuilder,
    private cookieService:CookieService,
    private route:ActivatedRoute,
    private router:Router,
  ) { }

  ngOnInit():void {
    this.loginFormGroup = this.formBuilder.group({
      usernameFormControl: new FormControl('', [
        Validators.required,
      ]),
      passwordFormControl: new FormControl('', [
        Validators.required,
      ]),
      rememberFormControl: new FormControl('', [
      ]),
    });
    this.usernameFormControl = this.loginFormGroup.controls.usernameFormControl;
    this.passwordFormControl = this.loginFormGroup.controls.passwordFormControl;
    this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
  }

  nextStep() {
    this.step = 2;
  }

  previousStep() {
    this.step = 1;
  }

  loginSuccess(data:any) {
    this.cookieService.delete('loginAuth');
    // if (this.checked) {
    //   this.cookieService.set('loginAuth', escape(JSON.stringify({
    //     name: this.usernameFormControl.value,
    //     pwd: this.passwordFormControl.value,
    //   })));
    // }
    this.loading = false;
    this.router.navigate([this.returnUrl]);
  }


  onLogin() {
    // this.loading = true;
    const login = this.authService.login(this.usernameFormControl.value, this.passwordFormControl.value, 'username');
    login.subscribe(
      (data:any) => {
        this.loginSuccess(data);
      }, (error) => {
        this.loading = false;
        throw error;
      },
    );
  }
}
