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 { ActivatedRoute } from '@angular/router';
declare var $: any;
@Component({
    selector: 'app-set-passwword',
    templateUrl: './set-passwword.component.html',
    styleUrls: ['./set-passwword.component.scss']
})
export class SetPasswwordComponent implements OnInit {
    setform: FormGroup;
    setchangeform: FormGroup;
    newpassword: any = '';
    repassword: any = '';
    oldpassword: any = '';
    password_error: string = '';
    passwordPattern = "^(?=.*?[a-z])(?=.*?[0-9]).{8,}$";
    type: any;
    sub: any;
    password_sucess: string = '';
    new_type = "password";
    repassword_type = "password";
    old_type = "password";
    show_textbox1 = false;
    show_textbox2 = false;
    show_textbox3 = false;
    set_from:string;
    constructor(private formBuilder: FormBuilder, private server: HyperService, private router: Router, private route: ActivatedRoute) {
        this.sub = this.route.params.subscribe(params => {
            this.type = params['type'];
            console.log('Type', this.type)
        });
    }
    ngOnInit() {
        this.sub = this.route.params.subscribe(params => {
            this.type = params['type'];
            console.log('Type', this.type)
        });
        if(this.type!=2){
            this.formBuild()
        }else{
            this.formChangeBuild()
        }
        if(LocalStorage.getValue('forgot')!=undefined) {
            this.set_from = LocalStorage.getValue('forgot')
        }
    }
    formChangeBuild(){
        this.setchangeform = this.formBuilder.group({
            oldpassword: [null, Validators.compose([Validators.required, Validators.pattern(this.passwordPattern)])],
            newpassword: [null, Validators.compose([Validators.required, Validators.pattern(this.passwordPattern)])],
            repassword: [null, Validators.compose([Validators.required])]
        });
    }
    formBuild() {
        this.setform = this.formBuilder.group({
            // oldpassword: [null, Validators.compose([Validators.required, Validators.pattern(this.passwordPattern)])],
            newpassword: [null, Validators.compose([Validators.required, Validators.pattern(this.passwordPattern)])],
            repassword: [null, Validators.compose([Validators.required])]
        });
    }

    onSetPassword() {
        if ((this.newpassword != this.repassword) && this.repassword!='') {
            this.password_error = "Password and confirm password not matching";
        } else {
            this.password_error=''
            this.onSet(this.type)
        }
    }


    toggleShow(textbox) {
        if (textbox == 1) {
            this.show_textbox1 = !this.show_textbox1;
            if (this.show_textbox1) {
                this.new_type = "text";
            } else {
                this.new_type = "password";
            }
        } else if(textbox == 2){
            this.show_textbox2 = !this.show_textbox2;
            if (this.show_textbox2) {
                this.repassword_type = "text";
            } else {
                this.repassword_type = "password";
            }

        }else{
            this.show_textbox3 = !this.show_textbox3;
            if (this.show_textbox3) {
                this.old_type = "text";
            } else {
                this.old_type = "password";
            }
        }

    }

    onSet(type) {

        console.log('type', type)
        if (type == 2) {
            if (this.setchangeform.valid) {
                console.log('1')
                let user_name;
                if(LocalStorage.getValue('signup_user')!=undefined){
                    user_name=LocalStorage.getValue('signup_user').username
                }else{
                    user_name=LocalStorage.getValue('smpin') 
                }
                this.server.post("user/change_password", {
                    new_password: this.newpassword,
                    current_password:this.oldpassword,
                    type: 'old',
                    username:user_name
                }).then((data) => {
                    console.log(data)
                    if (data.status == 200 && data.result.response == "success") {
                        this.password_sucess = data.result.message
                        setTimeout(() => {
                            this.router.navigateByUrl('');
                        }, 700);
                    }else if(data.status == 401 && data.result.response == "failed"){
                        this.router.navigateByUrl('');
                    } else if (data.result.response == "failed") {
                        this.password_error = data.result.message;
                    }
                })
            } else {
                this.validateAllFormFields(this.setchangeform);
            }
        } else if (type != 2) {
            console.log('2')
            let user_name;
                if(LocalStorage.getValue('signup_user')!=undefined){
                    user_name=LocalStorage.getValue('signup_user').username
                }else{
                    user_name=LocalStorage.getValue('smpin') 
                }
            if (this.setform.valid) {
                this.server.post("user/change_password", {
                    new_password: this.newpassword,
                    type: this.set_from,
                    username: user_name
                }).then((data) => {
                    if (data.status == 200 && data.result.response == "success") {
                        this.password_sucess = data.result.message;
                        if(this.set_from=='register') {
                            setTimeout(() => {
                                $('#mandatory').modal({
                                    backdrop: 'static',
                                    keyboard: false,
                                });
                                $("#mandatory").modal('show');
                            }, 200);
                        }else{
                            setTimeout(() => {
                                this.router.navigateByUrl('');
                            }, 700);
                        }
                        LocalStorage.setValue('user_data', data.result.data);
                        LocalStorage.setValue('token', data.result.access_token);
                    } else if (data.result.response == "failed") {
                        this.password_error = data.result.message;
                    }
                })
            } else {
                this.validateAllFormFields(this.setform);
            }
        }

    }

    isSubmit() {
        LocalStorage.setValue('loggedIn', true);
        LocalStorage.setValue('is_firsttime', true);
        setTimeout(() => {
            this.router.navigateByUrl('userprofile');
        }, 700);
    }


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

}