import { Component, OnInit ,ViewChild} from '@angular/core';
import * as moment from 'moment';
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 { BulletinDetailsComponent } from '../bulletin-details/bulletin-details.component';
import { Location } from '@angular/common';
declare var $: any;
import { Observable } from "rxjs/Observable";
import { Subscription } from "rxjs";

@Component({
  selector: 'app-wallet',
  templateUrl: './wallet.component.html',
  styleUrls: ['./wallet.component.scss']
})
export class WalletComponent implements OnInit {

  @ViewChild(BulletinDetailsComponent) content_modal: BulletinDetailsComponent;

  loader: boolean;
  order_history: any;
  sales_date: any;
  user_dashboard: any;
  percentage: any;
  otpform: FormGroup;
  otpform1:FormGroup;
  mpin:string='';
  walletpin:string='';
  confirm_mpin:string='';
  create_mpin:string='';
  mpin_error:boolean=false;
  mpin_error1:boolean=false;
  pin_error:boolean=false;
  current_amount:any;
  wallet_pin:string='';
  isForgotGetOtp:boolean=false;
  smpin_forgot: any = '';
  smpin_error:boolean=false;
  smpin_error1:boolean=false;
  isGetOtp:boolean=false;
  otp:any='';
  otp_error_data:boolean=false;
  otp_error:boolean=false;
  new_pin:boolean=false;
  isGetOtpChange:boolean=false;
  new_pin_change:boolean=false;
  pin_notmatch:boolean=false;
  old_pin:any='';
  error_msg:string='';
  resend_enable: boolean = false;
  countdown: any;
  loader_timing: any;
  loader_delay: any;
  isTimerRunning: boolean = false;
  otp_expiry:number;
  stream$;
  sub: Subscription
  mpin1: any;
  mpin2: any;
  mpin3: any;
  mpin4: any;
  otp1:any;
  otp2:any;
  otp3:any;
  otp4:any;
    cat_list: any;
    cat_list_id: any;

    
  constructor(private server: HyperService, private router: Router,private formBuilder: FormBuilder,private _location: Location) {
      this.wallet_pin= LocalStorage.getValue('wallet_pin');
      //this.wallet_pin= '';
      console.log(this.wallet_pin,"this.wallet_pin")
      if(this.wallet_pin=="" || this.wallet_pin==undefined){
          this.onClickForgotPin();
      }
      
  }

  ngOnInit() { 
    this.mpin1='';
    this.mpin2='';
    this.mpin3='';
    this.mpin4='';
    this.close();
    $('#pinModalCenter').modal({
        backdrop: 'static',
        keyboard: false
    })
    $('#pinModalCenter').modal('show');
    // if(this.wallet_pin=="" || this.wallet_pin==undefined){
    //     $('#pinModalCenter').modal('show');
    // }else{
    //     $('#pinModalCenter').modal('hide');
    // }
      
      this.orderHistoryList();
      this.getcategory();
      this.formBuild() 
      this.formBuildOtp() 
  } 
  formBuild() {
    this.otpform = this.formBuilder.group({
        mpin1: [null, Validators.compose([Validators.required])],
        mpin2: [null, Validators.compose([Validators.required])],
        mpin3: [null, Validators.compose([Validators.required])],
        mpin4: [null, Validators.compose([Validators.required])]
    });
}
formBuildOtp() {
    this.otpform1 = 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])]
    });
}
  onInputChange(){
    $('input.password').on('keyup', function(e) {
        if($(this).val()!='' && e.keyCode != 8){
        if ($(this).val()) {
            $(this).next().focus();
        }
    }else{
        if(e.keyCode == 8){ 
        // console.log($(this).val(),"$(this).val()sdf")
        $(this).prev().focus();
    }
    }
       
    });
}
  orderHistoryList() {
      this.loader = true
      this.server.get("dashboard/orderhistory?page=0&limit=10")
          .then((data) => {
              if (data.status == 200 && data.result.response != 'failed' ) {
                  this.loader = false;
                  this.order_history = data.result.data;
                  this.current_amount=data.result.current_amount;
                //   console.log(this.order_history,"this.order_history")
                //   LocalStorage.setValue('bullet_in', this.bullet_in)
                 
              } else if (data.result.status == 401 && data.result.response == 'failed') {
                  this.router.navigateByUrl('');
              }
          });
  }
  onSubmitPin(){
    console.log("mpin",this.confirm_mpin)
    if(this.confirm_mpin!='' && this.confirm_mpin.length==4 && this.confirm_mpin==this.create_mpin){
    this.pin_error=false;
    this.loader = true
    this.server.post("dashboard/changempin",{mpin:this.confirm_mpin})
        .then((data) => {
            if (data.status == 200 && data.result.response != 'failed' ) {
                this.loader = false;
                $('#pinModalCenter').modal('hide');
                LocalStorage.setValue('wallet_pin', this.confirm_mpin);
            } else if (data.result.status == 401 && data.result.response == 'failed') {
                this.router.navigateByUrl('');
            }
        });
    }else{
        this.pin_error=true;
    }
  }
  onSubmitPinChange(){
    console.log("mpin",this.confirm_mpin,this.wallet_pin,this.old_pin,this.create_mpin)
    if((this.confirm_mpin!='') && (this.confirm_mpin.length==4) && (this.confirm_mpin==this.create_mpin) && (this.wallet_pin==this.old_pin)){
    this.pin_error=false;
    this.loader = true
    this.server.post("dashboard/changempin",{mpin:this.confirm_mpin})
        .then((data) => {
            if (data.status == 200 && data.result.response != 'failed' ) {
                this.loader = false;
                this.old_pin='';
                this.new_pin_change=false;
                this.error_msg='';
                this.pin_notmatch=false;
                $('#pinModalCenter').modal('hide');
                LocalStorage.setValue('wallet_pin', this.confirm_mpin);
            } else if (data.result.status == 401 && data.result.response == 'failed') {
                this.router.navigateByUrl('');
            }
        });
    }else if(this.old_pin=='' && this.create_mpin=='' && this.confirm_mpin==''){
        this.error_msg='';
        this.pin_notmatch=true;
        this.error_msg='Please enter all fields';
    }else if(this.old_pin==''){
        this.error_msg='';
        this.pin_notmatch=true;
        this.error_msg='Enter Old PIN';
    }else if((this.wallet_pin!=this.old_pin) && this.old_pin!=''){
        this.error_msg='';
        this.pin_notmatch=true;
        this.error_msg='Old PIN not matched';
    }else if(this.create_mpin==''){
        this.error_msg='';
        this.pin_notmatch=true;
        this.error_msg='Enter Create PIN';
    }else if(this.confirm_mpin==''){
        this.error_msg='';
        this.pin_notmatch=true;
        this.error_msg='Enter Confirm PIN';
    }  else if(this.create_mpin==''){
        this.error_msg='';
        this.pin_notmatch=true;
        this.error_msg='Enter Create PIN';
    } else if(this.confirm_mpin!=this.create_mpin){
        this.error_msg='';
        this.pin_notmatch=true;
        this.error_msg='Entered new PIN has not matched';
    }else {
        this.error_msg='error';
        this.pin_notmatch=true;
    }
  }
 
onSubmitOtp(){
    // console.log("mpin",this.mpin)
    // if(this.mpin!='' && this.mpin.length==4 && this.mpin==this.wallet_pin){
    // this.mpin_error=false;
    // this.mpin_error1=false;
    // this.loader = true
    // this.server.post("dashboard/changempin",{mpin:this.mpin})
    //     .then((data) => {
    //         if (data.status == 200 && data.result.response != 'failed' ) {
    //             this.loader = false;
    //             $('#pinModalCenter').modal('hide');
               
    //         } else if (data.result.status == 401 && data.result.response == 'failed') {
    //             this.router.navigateByUrl('');
    //         }
    //     });
    // }else if(this.mpin==''){
    //     this.mpin_error1=true;
    // }else{
    //     this.mpin_error=true;
    // }
    this.walletpin = (this.mpin1.toString())+(this.mpin2.toString())+(this.mpin3.toString())+(this.mpin4.toString());
    if (this.otpform.valid) {
        if(this.walletpin==this.wallet_pin){
            this.mpin_error=false;
            this.mpin_error1=false;
            this.loader = true
            this.server.post("dashboard/changempin",{mpin:this.walletpin})
            .then((data) => {
                console.log(data)
                if (data.status == 200 && data.result.response == 'success' ) {
                    this.loader = false;
                    $('#pinModalCenter').modal('hide');
                } else if (data.result.status == 401 && data.result.response == 'failed') {
                    this.router.navigateByUrl('');
                }else if (data.result.response == "failed") {
                    this.mpin_error=true;
                    this.mpin_error1=false;
                    // this.mpin_error1 =  data.result.message;
                }
            })
        }else{
            this.mpin_error=true;
            this.mpin_error1=false;
        }
        
    } else {
        this.mpin_error1=true;
        this.mpin_error=false;
        this.validateAllFormFields(this.otpform);
    }
}
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);
        }
    });
}
onGetOtp(){
 if(this.smpin_forgot!=''){
    this.smpin_error=false;
    this.smpin_error1=false;
    this.loader = true
    this.server.post("user/forgot_password",{ username: this.smpin_forgot})
        .then((data) => {
            if (data.status == 200 && data.result.response != 'failed' ) {
                this.loader = false;
            //    this.wallet_pin='';
               this.isForgotGetOtp=false;
               this.new_pin=false;
               this.isGetOtp=true;
                // LocalStorage.setValue('wallet_pin', this.confirm_mpin);
            } else if(data.result.status == 406 && data.result.response == 'failed'){
                this.loader = false;
                this.smpin_error1=true;
                this.smpin_error=false;
            }else if (data.result.status == 401 && data.result.response == 'failed') {
                this.router.navigateByUrl('');
            }
        });
    }else{
        this.smpin_error=true;
        this.smpin_error1=false;
    }
  }
  onSubmitGetOtp(){
      
    // if(this.otp!=''){
    //     this.otp_error_data=false;
    //     this.otp_error=false;
    //     this.isGetOtp=true;
    //     this.loader = true;
        // this.server.post("user/otp_validation",{ type: 'mpin',otp: this.otp})
        //     .then((data) => {
        //         if (data.status == 200 && data.result.response != 'failed' ) {
        //             this.loader = false;
        //              this.isGetOtp=false;
        //              this.new_pin=true;
        //         } else if(data.result.status == 406 && data.result.response == 'failed'){
        //             this.loader = false;
        //             this.otp_error_data=true;
        //             this.otp_error=false;
        //         }else if (data.result.status == 401 && data.result.response == 'failed') {
        //             this.router.navigateByUrl('');
        //         }
        //     });
    //     }else{
    //         this.otp_error=true;
    //         this.otp_error_data=false;
    //     }
    if (this.otpform1.valid) {
        this.otp_error_data=false;
        this.otp_error=false;
        this.isGetOtp=true;
        this.loader = true;
        this.server.post("user/otp_validation",{ type: 'mpin',otp: (this.otp1.toString())+(this.otp2.toString())+(this.otp3.toString())+(this.otp4.toString())})
            .then((data) => {
                if (data.status == 200 && data.result.response != 'failed' ) {
                    this.loader = false;
                     this.isGetOtp=false;
                     this.new_pin=true;
                } else if(data.result.status == 406 && data.result.response == 'failed'){
                    this.loader = false;
                    this.otp_error_data=true;
                    this.otp_error=false;
                }else if (data.result.status == 401 && data.result.response == 'failed') {
                    this.router.navigateByUrl('');
                }
            });
    } else {
        this.otp_error=true;
        this.otp_error_data=false;
        this.validateAllFormFields(this.otpform);
    }
  }
    test(i){
        setTimeout(() => {
        }, 1000);
  }
  close(){
      var i=0;
      for(i=0;i<3;i++){
          this.test(i)
      }
  }
  
  onSubmitGetOtpChange(){
    if (this.otpform1.valid) {
        this.otp_error_data=false;
        this.otp_error=false;
        this.isGetOtp=false;
        this.isGetOtpChange=true;
        this.loader = true;
        this.server.post("user/otp_validation",{ type: 'mpin',otp: (this.otp1.toString())+(this.otp2.toString())+(this.otp3.toString())+(this.otp4.toString())})
            .then((data) => {
                if (data.status == 200 && data.result.response != 'failed' ) {
                    this.loader = false;
                    this.isGetOtpChange=false;
                    this.otp='';
                    this.isGetOtp=false;
                    this.new_pin_change=true;
                } else if(data.result.status == 406 && data.result.response == 'failed'){
                    this.loader = false;
                    this.otp_error_data=true;
                    this.isGetOtp=false;
                    this.otp_error=false;
                }else if (data.result.status == 401 && data.result.response == 'failed') {
                    this.router.navigateByUrl('');
                }
            });
        }else{
            this.otp_error=true;
            this.otp_error_data=false;
            this.validateAllFormFields(this.otpform1);
        }
  }
  onClickCancelSMpin(){
    this.isForgotGetOtp=false;
}
onClickCancelOtp(){
    this.isGetOtp=false;
    this._location.back();
    $('#pinModalCenter').modal('hide');
    // this.isForgotGetOtp=true;
}
onClickCancel(){
    $('#pinModalCenter').modal('hide');
    this.otp_error=false;
    this.otp_error_data=false;
    // this.router.navigateByUrl('bulletin');
    this._location.back();
}
getcategory(){
    this.server.get("redeem/category")
        .then((data) => {
            if (data.status == 200 && data.result.response != 'failed' ) {
              console.log(data);
                this.loader = false;
                this.cat_list = data.result.data.root_category;
                this.cat_list_id = this.cat_list.category_id; 
            } else if (data.result.status == 401 && data.result.response == 'failed') {
                this.router.navigateByUrl('');
            }
        });
}
onClickPurchase(){
    // this.router.navigateByUrl('wallet/category_list');
    this.router.navigateByUrl('wallet/product_list/'+this.cat_list_id);
}
onClickChangePin(){
    this.onclose();
    this.loader = true;
    this.otp='';
    this.create_mpin='';
    this.confirm_mpin='';
    this.new_pin=false;
    this.isGetOtp=false;
    this.isGetOtpChange=true;
    this.server.get("user/mpin_otp")
    .then((data) => {
        if (data.status == 200 && data.result.response != 'failed' ) {
            this.loader = false;
            this.resend_enable=false;
            this.TimeSet(data.result.data.otp_expiry)
        } else if (data.result.status == 401 && data.result.response == 'failed') {
            this.router.navigateByUrl('');
        }
    });
    $('#pinModalCenter').modal('show');
    
}
onClickCancelOtpNew(){
    $('#pinModalCenter').modal('hide');
    this.isGetOtpChange=false;
    this.new_pin_change=false;
    this.pin_notmatch=false;
    this.otp1='';
    this.otp2='';
    this.otp3='';
    this.otp4='';
    this.otp_error_data=false;
    this.otp_error=false;
}
onClickForgotPin(){
    // $('#pinModalCenter').modal('show');
    // this.wallet_pin='';
    this.otp='';
    this.create_mpin='';
    this.confirm_mpin='';
    this.new_pin=false;
    this.isGetOtp=true;
    this.server.get("user/mpin_otp")
    .then((data) => {
        if (data.status == 200 && data.result.response != 'failed' ) {
            this.loader = false;
            this.resend_enable=false;
            this.TimeSet(data.result.data.otp_expiry)
        } else if (data.result.status == 401 && data.result.response == 'failed') {
            this.router.navigateByUrl('');
        }
    });
}
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;
    
}
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;
    }
}
resend:boolean;
resendOtp() {
    this.resend = true;
    this.resend_enable = false;
    this.onClickForgotPin();
}
}