import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { HyperService } from './../../core/services/http.service';
import { LocalStorage } from './../../core/services/local_storage.service';
import { Router } from "@angular/router";
import { timer } from 'rxjs/observable/timer';
import { take, map } from 'rxjs/operators';
import { Observable } from "rxjs/Observable";
import "rxjs/add/observable/timer";
import "rxjs/add/operator/finally";
import "rxjs/add/operator/takeUntil";
import "rxjs/add/operator/map";
import { Subscription } from "rxjs";
import { TimerObservable } from "rxjs/observable/TimerObservable";
import { ViewChild, AfterViewInit, Renderer } from '@angular/core';
import { CONFIG } from '../../config';

declare var $: any;
@Component({
    selector: 'app-forgot-password',
    templateUrl: './forgot-password.component.html',
    styleUrls: ['./forgot-password.component.scss']
})
export class ForgotPasswordComponent implements OnInit {
    stream$
    sub: Subscription
    otp_error: string;
    otp_sucess: boolean = false;
    otpform: FormGroup;
    forgot_otp: string = '';
    forgot_otp1: any;
    forgot_otp2: any;
    forgot_otp3: any;
    forgot_otp4: any;
    resend: boolean = false;
    resend_enable: boolean = false;
    forgot_user: any;
    countdown: any;
    loader_timing: any;
    loader_delay: any;
    isTimerRunning: boolean = false;
    otp_expiry:number;
    mobileno_start:any;
    mobileno_end:any;
    constructor(public renderer: Renderer,private formBuilder: FormBuilder, private server: HyperService, private router: Router) {
        //this.TimeSet(5)

     }

    ngOnInit() {

        this.formBuild();
        this.forgot_otp1='';
        this.forgot_otp2='';
        this.forgot_otp3='';
        this.forgot_otp4='';
        // this.otp_error='';

    }

    callInitViews(){
        this.countdown = ''
        if(LocalStorage.getValue('forgot_data')!=undefined){
            this.forgot_user = LocalStorage.getValue('forgot_data');
            this.mobileno_start = this.forgot_user.data.substring(0, 2)
            this.mobileno_end = this.forgot_user.data.substring(8, 11)
            this.otp_expiry = this.forgot_user.otp_expiry;
        }
        if(CONFIG.forgot_cont==true){
            this.isTimerRunning = false
            this.TimeSet(this.otp_expiry)
        }
    }

    ngAfterContentChecked(){
        if(CONFIG.forgot_cont==true){
            if (!this.isTimerRunning && LocalStorage.getValue('forgot_data') != undefined){
                this.callInitViews()
                this.isTimerRunning = true
            }
        }
    }

    formBuild() {
        this.otpform = this.formBuilder.group({
            forgot_otp1: [null, Validators.compose([Validators.required])],
            forgot_otp2: [null, Validators.compose([Validators.required])],
            forgot_otp3: [null, Validators.compose([Validators.required])],
            forgot_otp4: [null, Validators.compose([Validators.required])]
        });
    }

    resendOtp() {
        this.resend = true;
        this.resend_enable = false;
        this.forgot_otp1='';
        this.forgot_otp2='';
        this.forgot_otp3='';
        this.forgot_otp4='';
        this.otp_error='';
        this.forgotOtp();
    }


    forgotOtp() {
        let pin=LocalStorage.getValue('smpin');
        if (pin == undefined || pin == '' || pin == null) return;
        this.server.post("user/forgot_password", {
            username: pin
        }).then((data) => {
            LocalStorage.setValue('forgot_data', data);
            if (data.status == 200 && data.result.response == "success") {
                this.resend_enable=false;
                this.TimeSet(data.result.otp_expiry)
            } else if (data.result.response == "failed") {

            }
        })
    }

    TimeSet(Time) {
        this.loader_timing = Time * 60;
        this.loader_delay = this.loader_timing / 2;
        const interval = 1000;
        const duration = 10 * 6000 * Time;
        this.stream$ = Observable.timer(0, interval)
            .finally(() => this.onclose())
            .takeUntil(Observable.timer(duration + interval))
            .map(value => duration - value * interval);
            this.sub = this.stream$.subscribe(value => this.formatMin(value));
    }

    onclose() {
        this.countdown = ''
        this.resend_enable = true;

    }
    onInputChange(){
        $('input.password').on('keyup', function(e) {
            if($(this).val()!='' && e.keyCode != 8){
            if ($(this).val()) {
                console.log($(this).val(),"$(this).val()")
                $(this).next().focus();
            }
        }else{
            if(e.keyCode == 8){
            // console.log($(this).val(),"$(this).val()sdf")
            $(this).prev().focus();
        }
        }

        });
    }
    onSubmitOtp() {
        LocalStorage.removeValue('token')
        console.log(this.otpform.valid)
        if (this.otpform.valid) {
            this.server.post("user/otp_validation", {
                otp: (this.forgot_otp1.toString())+(this.forgot_otp2.toString())+(this.forgot_otp3.toString())+(this.forgot_otp4.toString()),
                type: 'forgot_password',
                username: LocalStorage.getValue('smpin')
            }).then((data) => {
                if (data.status == 200 && data.result.response == "success") {
                    this.otp_sucess = true;
                    LocalStorage.setValue('token', data.result.access_token);
                    LocalStorage.setValue('forgot', 'change');
                    $("#fogotexampleModalCenter").modal('hide');
                    this.router.navigateByUrl('setpassword');
                } else if (data.result.response == "failed") {
                    this.otp_error =  data.result.message;
                }
            })
        } else {
            this.otp_error = '';
            this.validateAllFormFields(this.otpform);
        }
    }

    formatMin(s) {
        let ms = s % 1000;
        s = (s - ms) / 1000;
        let secs = s % 60;

        s = (s - secs) / 60;
        let mins = s % 60;
        let hrs = (s - mins) / 60;
        if (hrs > 0) {
            this.countdown = hrs + ':' + mins + ':' + secs;
        } else {
            this.countdown = mins + ':' + secs;
        }
    }

    validateAllFormFields(formGroup: FormGroup) {
        Object.keys(formGroup.controls).forEach(field => {
            const control = formGroup.get(field);
            if (control instanceof FormControl) {
                control.markAsTouched({
                    onlySelf: true
                });
            } else if (control instanceof FormGroup) {
                this.validateAllFormFields(control);
            }
        });
    }

    // gotoChangePassword() {
    //     this.router.navigateByUrl('setpassword/2');
    // }
    onCancelOtp(){
        $("#fogotexampleModalCenter").modal('hide');
        this.forgot_otp = '';
        this.countdown = '';
        this.otpform.markAsUntouched();
        CONFIG.forgot_cont = false;
        this.sub.unsubscribe()
        this.sub = this.stream$.subscribe(0 , this.formatMin(0));
        this.isTimerRunning = false;
        this.forgot_otp1='';
        this.forgot_otp2='';
        this.forgot_otp3='';
        this.forgot_otp4='';
        this.otp_error='';
        this.resend_enable = false;
    }

}
