import { Component, OnInit } from '@angular/core';
import { LocalStorage } from './../../core/services/local_storage.service';
import { CONFIG } from '../../config';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { HyperService } from './../../core/services/http.service';
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 { Router } from "@angular/router";
import { ViewChild, ElementRef } from '@angular/core';

declare var $: any;

@Component({
    selector: 'app-signup-modal',
    templateUrl: './signup-modal.component.html',
    styleUrls: ['./signup-modal.component.scss']
})
export class SignupModalComponent implements OnInit {
    @ViewChild('closeBtn') closeBtn: ElementRef;
    otpform: FormGroup;
    otp:any;
    otp1: any;
    otp2: any;
    otp3: any;
    otp4: any;
    section: number;
    user_mobile: any;
    countdown: string;
    loader_timing: any;
    loader_delay: any;
    otp_error: string = '';
    otp_sucess: boolean = false;
    resend:boolean=false;
    resend_enable:boolean=false;
    sub: Subscription;
    stream$;
    isTimerRunning: boolean = false;
    constructor(private formBuilder: FormBuilder, private server: HyperService, private router: Router) {
        console.log("here")
    }

    ngOnInit() {
        // $('#fogotexampleModalCenter').modal({
        //     backdrop: 'static',
        //     keyboard: false
        // })
        this.formBuild();
    }
    
    formBuild() {
        this.otpform = this.formBuilder.group({
            otp1: [null, Validators.compose([Validators.required])],
            otp2: [null, Validators.compose([Validators.required])],
            otp3: [null, Validators.compose([Validators.required])],
            otp4: [null, Validators.compose([Validators.required])]   
        });
    }

    accept() {
        this.section = 1;
        console.log(this.section)
        this.signUpOtp();
    }

    reject() {
        this.section=null;
        $("#exampleModalCenter").modal('hide');
        this.countdown = '';
        this.otpform.markAsUntouched();
        CONFIG.forgot_cont = false;
        console.log(CONFIG.forgot_cont)
        this.resend_enable=false;
        this.otp_error = '';
        this.otp1 = ''
        this.otp2=""
        this.otp3=""
        this.otp4=""
    }

    modelClose(){
        this.countdown=''
        this.section =null;
    }

    resendOtp() {
        this.resend=true;
        this.resend_enable=false;
        this.signUpOtp();
    }

    contactDealer(){
        this.section =null;
    }

    signUpOtp() {
        this.server.post("user/signup_otp", {
            username: LocalStorage.getValue('signup_user').username
        }).then((data) => {
            console.log(data)
            if (data.status == 200 && data.result.response == "success") {
                let user_data = LocalStorage.getValue('signup_user');
                console.log(user_data.mobile,user_data.mobile.substring(0, 2)),user_data.mobile.substring(7, 10)
                this.user_mobile = user_data.mobile.substring(0, 3) + 'xxxx' + user_data.mobile.substring(7, 10);
                this.TimeSet(data.result.data.otp_expiry)
            } else if (data.result.response == "failed") {

            }
        })
    }

    TimeSet(Time) {
        this.loader_timing = Time * 60;
        this.loader_delay = this.loader_timing / 2;
        console.log('Testarstars', this.loader_timing)
        console.log('Testarstars', this.loader_delay)
        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;
    }

    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;
        }
    }
    onInputChange(){
        console.log("here1111")
        $('input.password').on('keyup', function() {
            if ($(this).val()) {
                $(this).next().focus();
            }
        });
    }
    onSubmitOtp() {
        if (this.otpform.valid) {
            this.server.post("user/otp_validation", {
                otp: (this.otp1.toString())+(this.otp2.toString())+(this.otp3.toString())+(this.otp4.toString()),
                type: 'register',
                username: LocalStorage.getValue('signup_user').username
            }).then((data) => {
                console.log(data)
                if (data.status == 200 && data.result.response == "success") {
                    console.log('OTP VERIFIED')
                    this.otp_sucess = true;
                    LocalStorage.setValue('token', data.result.access_token); 
                    LocalStorage.setValue('forgot', 'register'); 
                } else if (data.result.response == "failed") {
                    console.log('OTP not VERIFIED'+data.result.message)
                    this.otp_error =  data.result.message;
                }
            })
        } else {
            this.validateAllFormFields(this.otpform);
        }
    }

    gotoSetPassword() {
        this.router.navigateByUrl('setpassword');
    }

    validateAllFormFields(formGroup: FormGroup) {
        Object.keys(formGroup.controls).forEach(field => {
            console.log(field);
            const control = formGroup.get(field);
            if (control instanceof FormControl) {
                control.markAsTouched({
                    onlySelf: true
                });
            } else if (control instanceof FormGroup) {
                this.validateAllFormFields(control);
            }
        });
    }
    onCancelOtp(){
        this.section=null;
        $("#exampleModalCenter").modal('hide');
        this.countdown = '';
        this.otpform.markAsUntouched();
        CONFIG.forgot_cont = false;
        console.log(CONFIG.forgot_cont)
        this.sub.unsubscribe()
        this.sub = this.stream$.subscribe(0 , this.formatMin(0));
        this.resend_enable=false;
        this.otp_error = '';
        this.otp1 = ''
        this.otp2=""
        this.otp3=""
        this.otp4=""
    }
}