import {Component, Inject, OnDestroy, OnInit, Optional} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';

import {Router} from '@angular/router';
import {GlobalService} from '../../../classes/global.service';
import {AuthService} from '../../../classes/auth.service';
import {Dialog} from '../../../classes/dialog';

@Component({
  selector: 'app-submit-code',
  templateUrl: './submit.component.html',
  styleUrls: ['./submit.component.scss']
})
export class SubmitComponent implements OnInit, OnDestroy {
  smstoken = new FormControl('', [Validators.required]);
  email = new FormControl('', [Validators.required]);
  emailCtrl;
  public form: FormGroup;
  timeLeft: number = 60;
  interval;
  timer: boolean;

  constructor(private fb: FormBuilder,
              private global: GlobalService,
              private  auth: AuthService,
              private  router: Router,
              private  dialog: Dialog,
  ) {
    // for test
    this.timer = true;
    this.emailCtrl = this.global.emailData;
    console.log('emaildata', this.global.emailData);
    this.interval = setInterval(() => {
      if (this.timeLeft > 0) {
        this.timeLeft--;
        if (this.timeLeft == 0) {
          // for test
          this.timer = false;
        }
      } else {
        this.timeLeft = 60;
      }
    }, 1000);
  }

  ngOnInit() {
    this.form = this.fb.group({
      smstoken: this.smstoken,
      email: this.email,
    });
  }

  onSubmit() {
    this.global.smstoken = this.form.controls['smstoken'].value;
    this.auth.forgotPass3(this.global.emailData, '1', this.form.controls['smstoken'].value).subscribe(x => {
      const t = JSON.parse(x._body);
      if (t['allowed'] === true) {
        this.router.navigate(['/auth/newpassword']);
      } else this.dialog.openForAlert('کد وارد شده صحیح نمی باشد ');
    }, error => {
      console.log('erro ', error);
    }
    );
  }

  forgotPass() {
    this.auth.forgotPass2(this.global.emailData, '1', '1').subscribe(x => {
      console.log(x) ,
        success => {
          console.log(success);
        } , error => {
        this.dialog.openForAlert('کد ارسال نشد')
        console.log('error', error);
      };
    });
  }

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

  ngOnDestroy() {

  }
}
