import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { HyperService } from './../../core/services/http.service';
import { Router } from "@angular/router";
import { LocalStorage } from './../../core/services/local_storage.service';
import { CONFIG } from '../../config';
import { ForgotPasswordComponent } from '../forgot-password/forgot-password.component';

declare var $: any;

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss'],
    host: {
        '(document:click)': 'onClick($event)',
      }
})
export class LoginComponent implements OnInit { 
    fogotexampleModalCenter;
    lform: FormGroup;
    smpin: any;
    smpinid: any = '';
    password: any;
    signin_error: string = '';
    signup_error: string = '';
    forgot_error: string = '';
    viewSignUp: boolean = false;
    viewSignIn: boolean;
    signUpSubmit: boolean = false;
    user_mobile: any = {};
    viewForgot: boolean = false;
    smpin_forgot: any = '';
    forgot_Submit: boolean = false;
    show_info: boolean = false;
    type = "password";
    show = false;
    signIn_click:boolean=false;
    show_div: boolean;
    
    constructor(private formBuilder: FormBuilder, private server: HyperService, private router: Router) { 
        this.onClear()
        // this.getBanner()
    }

    ngOnInit() {
        this.onClear()
        this.formBuild();
        LocalStorage.setValue('loggedIn', false);
    }
    onClick(event) {
        if (event.target.className=='login' || event.target.className=='login_box' || event.target.className=='form-group' || event.target.className=='top_icon' || event.target.className=='form-control'|| event.target.className=='form3' || event.target.className=='star_logo' || event.target.className=='form1'){
           this.show_info=false;
       }
    }
    onClear() {
        LocalStorage.createJWT(); 
    }

    formBuild() {
        this.lform = this.formBuilder.group({
            smpin: [null, Validators.compose([Validators.required])],
            password: [null, Validators.compose([Validators.required])]
        });
    }

    goToSingUp() {
        this.viewSignUp = true;
        this.signUpSubmit = false;
        this.signin_error = '';
        this.signIn_click=false;
    }

    goToLogin() {
        this.formBuild();
        this.viewSignUp = false;
        this.viewSignIn = true;
        this.signup_error = '';
        this.smpinid = '';
    }

    backToLogin() {
        this.formBuild();
        this.viewForgot = false;
        this.viewSignIn = true;
        this.signup_error = '';
        this.smpin_forgot = '';
        this.forgot_Submit = false;
        this.forgot_error = '';
    }

    toggleShow() {
        //show view password toggle icon
        this.show = !this.show;
        if (this.show) {
            this.type = "text";
        } else {
            this.type = "password";
        }
    }

    showInfo() {
        this.show_info = !this.show_info;
    }

    onSignUp() {
        this.signUpSubmit = true;
        CONFIG.forgot_cont = true;
        this.show_div = CONFIG.forgot_cont;
        if (this.smpinid == undefined || this.smpinid == '' || this.smpinid == null) return;
        this.server.post("user/signup", {
            username: this.smpinid
        }).then((data) => {
            if (data.status == 200 && data.result.response == "success") {
                LocalStorage.setValue('signup_user', data.result.data);
              
                let mobileno_start = data.result.data.mobile.substring(0, 3)
                let mobileno_end = data.result.data.mobile.substring(7, 11)
                setTimeout(() => {
                    // $('#exampleModalCenter').modal({
                    //     keyboard: false,
                    // });
                    $("#exampleModalCenter").modal('show');
                    $("#userMobile").text(mobileno_start + 'xxxx' + mobileno_end);
                }, 200);
            } else if(data.status == 406 ) {
                this.signup_error = data.result.message;
            }
        })
    }

    onSignIn() {
        this.signIn_click=true; 
        if (this.lform.valid) {
            this.server.post("user/signin", {
                username: this.smpin.trim(),
                password: this.password
            }).then((data) => {
                    if (data.status == 200 && data.result.response == "success") {

                        console.log("data.result.data---->",data.result);
                        LocalStorage.setValue('pinvalue','');
                          LocalStorage.setValue('enquirymodulestatus', data.result.data.is_enquirymodule);
                    //    LocalStorage.setValue('enquirymodulestatus', '1');
                        
                        LocalStorage.setValue('selecteduseremail', data.result.data.dealer.email);
                        LocalStorage.setValue('selecteduseraddress', data.result.data.dealer.address);



                        LocalStorage.setValue('selecteduserrole', data.result.data.role);
                        LocalStorage.setValue('selecteddsename', data.result.data.dealer.dealer_name);
                        LocalStorage.setValue('selecteddsephone', data.result.data.dealer.phone);
                        LocalStorage.setValue('selecteddsecity', data.result.data.dealer.city);
                        LocalStorage.setValue('selecteddsecountry', data.result.data.dealer.country);
                        LocalStorage.setValue('selecteddsestate', data.result.data.dealer.state);
                        LocalStorage.setValue('selecteddealercode', data.result.data.dealer.dealer_code);
                        console.log("data.result.data.dealer.dealer_code",data.result.data.dealer.dealer_code);

                      //  console.log("data---->",data);
                        LocalStorage.setValue('token', data.result.access_token);
                        LocalStorage.setValue('user_data', data.result.data);
                     //   console.log(LocalStorage.getValue('user_data'))
                        LocalStorage.setValue('signup_user', data.result.data);
                        LocalStorage.setValue('wallet_pin', data.result.data.mpin);
                        LocalStorage.setValue('enquiry_pin', data.result.data.epin);
                        // console.log('wallet_pin',data.result.data.mpin,LocalStorage.getValue('wallet_pin'))
                        LocalStorage.setValue('loggedIn', true);
                        if (data.result.data.is_profile_updated == 0) {
                            LocalStorage.setValue('is_firsttime', true);
                            this.router.navigateByUrl('userprofile');
                        }
                        else if (data.result.data.is_profile_updated == 1) {
                            this.router.navigateByUrl('dashboard');
                        }
                    } 
                    else if (data.result.response == "failed") {
                        this.signin_error = data.result.message;
                    }
                })
        } 
        else {
            this.validateAllFormFields(this.lform);
            this.signin_error = '';
        }
    }

    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);
            }
        });
    }

    onForgotPassword() {
        this.signin_error=''
        this.viewForgot = true;
        this.signIn_click=false; 
    }

    forgotSubmit() { 
        CONFIG.forgot_cont = true;
        this.show_div = CONFIG.forgot_cont;
        LocalStorage.setValue('smpin', this.smpin_forgot); 
        this.forgot_Submit = true;
        if (this.smpin_forgot == undefined || this.smpin_forgot == '' || this.smpin_forgot == null) return;
        this.server.post("user/forgot_password", {
            username: this.smpin_forgot
        }).then((data) => {
            if (data.status == 200 && data.result.response == "success") {
                LocalStorage.setValue('forgot_data', data.result);
                let mobileno_start = data.result.data.substring(0, 2)
                let mobileno_end = data.result.data.substring(8, 11)
                CONFIG.forgot_user = LocalStorage.getValue('forgot_data');
                this.forgot_error='';
                if(CONFIG.forgot_user!=undefined){
                    setTimeout(() => {
                    $('#fogotexampleModalCenter').modal(ForgotPasswordComponent,{
                        backdrop: 'static',
                        keyboard: false,
                    });
                    
                    $("#fogotexampleModalCenter").modal('show');
                    
                    
                },1000)
            }
                
            } else if (data.result.response == "failed") {
                this.forgot_error = data.result.message
            }
        })
    }
   
    getBanner() {
      //  console.log("ernwlek")
        this.server.get("comments")
            .then((data) => {
                if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
                    
                } else if (data.result.status == 401 && data.result.response == 'failed') {
                    
                } else {
                     
                }
            });
    }
}