import { Component, OnInit, Input, ViewChild, ElementRef } from '@angular/core';
import { Card } from '../card.model';
import { NgForm, NgModel, FormBuilder, FormGroup, NgModelGroup, Validators } from '@angular/forms';

import { Observable } from 'rxjs/Observable';
import { Store } from '@ngrx/store';
import { AppState } from '../../../ecm-store/reducers';
import { HostUrlService } from '../../../host-url.service';

import { CreditCardValidator } from 'base-blocks';

import { CreditCard } from './credit-card';

declare var require: any;

@Component( {
    selector: 'card-screen',
    templateUrl: './card-screen.component.html',
    styleUrls: ['./card-screen.component.css']
})
export class CardScreenComponent implements OnInit {

    @Input() editMode: string = 'V';
    @Input() card: Card;
    @Input() isPaymentsPage: boolean = false;
    //@ViewChild('savecard') form: NgForm;
    
    @ViewChild('cardNumberEl') cardNumberEl: ElementRef;
    public target;
    
    cardForm: FormGroup;
    
    cardLength = 16;
    currentTime = new Date();
    currentYear: number = this.currentTime.getFullYear();
    
    cardDetails;

    constructor( private store: Store<AppState>, private _fb: FormBuilder, public hostUrlService : HostUrlService ){}

    ngOnInit() {
        this.cardForm = this._fb.group({
            creditCard: ['', [<any>CreditCardValidator.validateCCNumber]],
            expiryMonth: ['', [<any>Validators.required, <any>Validators.min(1), <any>Validators.max(12)]],
            expiryYear: ['', [<any>Validators.required, <any>Validators.min(this.currentYear)]],
            acctName: ['', [<any>Validators.required]],
            cvv: ['', [<any>Validators.required]]
          });
        
        if(this.editMode == 'V'){
           this.getCardDetails(this.card.acctNumber);
        }
        //this.form.addFormGroup(dir)
    }
    
    ngAfterViewInit(){
        if(this.editMode == 'V'){
            this.target = this.cardNumberEl.nativeElement;
            this.reFormatCardNumber(this.card.acctNumber);
        }
    }
    
    changeType($event){
        
        this.card.payServiceProvider = $event;
        
        console.log('Type==>',$event);
    }
    
    setCardLength($event){
        this.cardLength = $event + 3;
        
        console.log('Card Length==>',$event);
    }
    
    submitCard(card) {
        console.log('Submitted Card Data', card);
    }
    
    private reFormatCardNumber(e) {
        let formattedValue;
        let cardNumber = this.target.innerHTML;
        
        setTimeout(() => {
          console.log('this.target.value',cardNumber);
          let value = CreditCard.replaceFullWidthChars(cardNumber);
          value = CreditCard.formatCardNumber(value);
          console.log('--value--['+value+']');
          formattedValue = value.replace(/ /g, '-');
          this.target.selectionStart = this.target.selectionEnd = CreditCard.safeVal(value, this.target);
          this.target.innerHTML = this.creditCardMask(formattedValue);
        });
        
    }
    
    private creditCardMask(number, character = "X"){
        console.log('creditCardMask',number);
        //number = number.replace(/[^0-9]+/g, ''); /*ensureOnlyNumbers*/
        
        var firstOccurence = number.indexOf("-");
        var lastOccurence = number.lastIndexOf("-");
        console.log('Occurences',firstOccurence,lastOccurence);
        
        var l = number.length;
        return number.substring(0,firstOccurence+1) + character.repeat(l-8) + number.substring(lastOccurence,l);
    }
    
    getCardDetails(cardNumber){
        var lookup = require( 'binlookup' )();

        console.log( 'cardNumber[' + cardNumber + ']' );

        lookup( cardNumber ).then(
            data => {
                console.log( 'credit card details', data );
                this.card.bankName = data.bank.name;
            });
    }
    
}
