import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {HttpClient} from '@angular/common/http';
import {AuthService} from '../../../classes/servicess/auth.service';
import {Dialog} from '../../../classes/base_components/dialog/dialog';

@Component({
  selector: 'app-smstoken',
  templateUrl: './smstokenSignin.component.html',
  styleUrls: ['./smstokenSignin.component.scss']
})
export class SmstokenSigninComponent implements OnInit {
  showSms: Boolean = false;
  public form: FormGroup;
  mobileCtrl = new FormControl('', [Validators.required, Validators.minLength(4)]);
  passwordCtrl = new FormControl('', [Validators.required, Validators.minLength(4)]);
  timer: boolean;
  timeLeft: number = 60;
  interval;
  showTime: Boolean = false;
  remember: boolean = false;

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private http: HttpClient,
    private auth: AuthService,
    private dialog: Dialog,
  ) {
    this.form = this.fb.group({
      passwordCtrl: this.passwordCtrl,
      mobileCtrl: this.mobileCtrl,
    });

    this.timer = false;
  }

  ngOnInit() {
  }

  onSubmit() {
    // this.loading = true;
    this.auth.loginWithSmsToken(this.form.controls['mobileCtrl'].value,
      this.form.controls['passwordCtrl'].value
      , this.remember, '1', '1', '1')
      .subscribe(
        loggedIn => {
          if (loggedIn) {
            // this.loading = false;
            this.router.navigateByUrl('');
          }
        },
        error => {
          // console.log('errors', error);
          // this.loading = false;
          // let errors = error.json().errors;
          // setErrors(repairErrors(errors), this.form.controls, this.dialog);
        });
  }

  mobileExists() {
    this.getSmsToken();
  }

  receiveData() {
    this.timer = true;
    this.getSmsToken();
  }

  getSmsToken() {
    this.auth.mobileExists(this.form.controls['mobileCtrl'].value, '3').subscribe(res => {
      if (res['_body'] === '1') {
        this.showSms = true;
        this.showTime = true;
        this.timer = true;
        this.interval = setInterval(() => {
          if (this.timeLeft > 0) {
            this.timeLeft--;
            if (this.timeLeft == 0) {
              // for test
              this.timer = false;
            }
          } else {
            this.timeLeft = 60;
          }
        }, 1000);
      } else {
        this.form.controls['mobileCtrl'].setErrors({'error': 'کاربر مورد نظر یافت نشد '});
      }
    }, error => {
      console.log('error hast', error);
      this.dialog.openForAlert('دسترسی به سرور ممکن نیست');
      console.log('error');
    });
  }
}
