import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms';
import {AuthService} from '../../../public/services/auth.service';
import {Dialog} from '../../../public/dialog';

@Component({
  selector: 'app-signin',
  templateUrl: './signin.component.html',
  styleUrls: ['./signin.component.scss']
})
export class SigninComponent implements OnInit {
  usernameCtrl = new FormControl('', [Validators.required]);
  passwordCtrl = new FormControl('', [Validators.required]);
  public form: FormGroup;
  loading: boolean;

  constructor(private fb: FormBuilder,
              private router: Router,
              private auth: AuthService,
              private dialog: Dialog,
  ) {
    this.loading = false;
  }

  ngOnInit() {
    this.form = this.fb.group({
      usernameCtrl: this.usernameCtrl,
      passwordCtrl: this.passwordCtrl,
    });
    console.log('ooo' , this.auth.firebase);

  }

  onSubmit() {
    this.loading = true;
    this.auth.login(this.form.controls['usernameCtrl'].value,
      this.form.controls['passwordCtrl'].value
      , '1', this.auth.firebase)
      .subscribe(
        loggedIn => {
          if (loggedIn) {
            alert('لاگین شد ');
            this.loading = false;
            // this.router.navigateByUrl('/map/map');
            this.router.navigate(['/map/map']);
          }
        },
        error => {
          alert(error);
          console.log(error);
          this.loading = false;
          const p = error.json().errors;
          for (const key in p) {
            const err = p[key];
            console.log('hello', err);
            let errorKey = '';
            try {
              errorKey = (err.source.pointer).split('\/').reverse()[0];
            } catch (e) {
              errorKey = '';
            } finally {
              errorKey = '';
            }
            if (errorKey !== '' && (errorKey === 'mobile' || errorKey === 'email')) {

              this.form.controls['username'].setErrors({'error': err.detail});
            } else if (errorKey === 'password') {
              this.form.controls['password'].setErrors({'error': err.detail});
            } else {
              this.dialog.openForAlert(err.detail);
            }
          }

        });

  }
}

