import { Component, OnInit, ViewChild, ElementRef, Input, Output, EventEmitter ,DoCheck ,AfterViewInit, AfterViewChecked} from '@angular/core';
import { FormBuilder, Validators,NgForm,NgModel,FormGroup } from '@angular/forms';
import { ItemDetail } from '../../ecm-model/product-detail-model';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { Location } from '@angular/common';
import { MdSnackBar } from '@angular/material';
import {MatVerticalStepper} from '@angular/material/stepper';

import { Store } from '@ngrx/store';
import {AppState} from '../../ecm-store/reducers';
import { EcmCheckoutService } from './ecm-checkout.service';
import {CartActions, SavedCardAction, ProfileActions, AdressAction} from '../../ecm-store/actions';
import { Breadcrumbs } from '../../ecm-breadcrumbs/ecm-breadcrumbs.component';
import { Card } from '../../user-card/card-manager/card.model';
import { Address } from '../../user-address/address-manager/address.model';
import { Item } from '../../ecm-model/product-model';
import { CardScreenComponent } from '../../user-card/card-manager/card-screen/card-screen.component';
import { AddressScreenComponent } from '../../user-address/address-manager/address-screen/address-screen.component';
import { EcmPanelComponent } from '../ecm-panel/ecm-panel.component';
import { EcmCartService } from '../ecm-cart/ecm-cart.service';


 export class CustomerInformation {  
        public soldTo:string = '';
        public billTo:string = '';
        public deliverTo:string = '';
        public orderNo:string = '';
        public orderDate:string = '';
        public shipDate:string = '';
        public dueDate:string = '';

}
    
@Component( {
    selector: 'ecm-checkout',
    templateUrl: './ecm-checkout.component.html',
    styleUrls: ['./ecm-checkout.component.css'], 
    providers:[EcmCheckoutService]
})
export class EcmCheckoutComponent implements OnInit ,DoCheck  {
    dataSource = '/ibase/ecm/service/customers/'
    
    @ViewChild('userForm') currentForm: NgForm;
    @Input() unAuthorized: boolean = false;
    
    checked = false;
    totalPrice:number = 0;
    cartItems;
    userData: any;
    singleProduct;
    selectedStep;
    orderReviewed;
    selectedAddressOpt;
    ecmType; //chitra
    
    @ViewChild( 'cardScreen' ) child: CardScreenComponent;
    @ViewChild('addrAddScreen') addScreen: AddressScreenComponent;
    @ViewChild('stepper') stepper: MatVerticalStepper;
    @ViewChild( 'ecmPanel' ) ecmPanel: EcmPanelComponent;

    redirect : boolean = false;
    cardList;
    newCard: Card = new Card();
    selectedPaymntOpt;
    addressList;
    newAddress: Address = new Address();
    selectedAddress: Address;
    userInfo;
    cvv;
    public childForm;
    public editForm;
    address;
    addressObj;
    
    loginFormGroup: FormGroup;
    addressFormGroup: FormGroup;
    reviewOrdersFormGroup: FormGroup;
    cardFormGroup: FormGroup;
    customerInformationFormGroup : FormGroup;
    customerInformation;
    
    
    constructor(private formBuilder: FormBuilder, private store: Store<AppState>,public checkoutService: EcmCheckoutService,private _location: Location, private cartActions: CartActions, public breadcrumbSerivce: Breadcrumbs, private cardActions: SavedCardAction, private profileActions: ProfileActions, private addressActions: AdressAction, public snackBar: MdSnackBar, private _formBuilder: FormBuilder) {
                 this.store.dispatch(this.profileActions.loadProfile());
                 this.store.dispatch(this.addressActions.loadAddress());
                 this.store.dispatch(this.cardActions.loadSavedCards());
        
                 this.customerInformation = new CustomerInformation();//chitra
    }

    ngOnInit() {
        
        this.ecmType= localStorage.getItem( 'ECM_TYPE' );
        console.log("ecmType exist in local storage",this.ecmType);
 
        console.log("selectedAddressOpt -- >",this.selectedAddressOpt);
        this.store.dispatch(this.addressActions.loadAddress());
        this.store.dispatch(this.cardActions.loadSavedCards());
        window.scrollTo(0,0);
        this.createUserData();
        this.getCartItems();
        
        if(this.checkoutService.getItem()){
            this.cartItems = [];
            this.cartItems.push(this.checkoutService.getItem());
            this.checkoutService.reset();
            
            this.cartItems.forEach(
                    item => { 
                        this.totalPrice = this.totalPrice + (parseFloat( item.itemHeader.itemDiscountedRate ) * item.itemQuantity);
                    }
            );
           
        }else {
            this.getCartItems();
        }
        
        
        
        this.userInfo = this.store.select('profileInfo');
        
        this.store.select('Address').subscribe( addressList => {
            console.log( 'loadUser addressList >> ', addressList );
            this.addressList = addressList;
            this.selectedAddressOpt = addressList[0];
        });
        
        this.store.select('savedCards').subscribe( cardList => {
            console.log( 'loadUser cardList >> ', cardList );
            this.cardList = cardList;
            if(cardList[0]){
                this.selectedPaymntOpt = cardList[0].lineNo;
            }
        });
        
        this.stepper.selectionChange.subscribe(
                selected => {
                    this.selectedStep = selected;
                    console.log("selected step",selected);
                }
        );
        
        this.loginFormGroup = this._formBuilder.group({
            userData: ['', Validators.required]
          });
        this.addressFormGroup = this._formBuilder.group({
            address: ['', Validators.required]
        });
        
        this.reviewOrdersFormGroup = this._formBuilder.group({
            orderReviewed: ['', Validators.required]
        });
        
        this.cardFormGroup = this._formBuilder.group({
            cvv: ['', Validators.required]
        });
        
        /*chitra */
        this.customerInformationFormGroup = this._formBuilder.group({
            soldTo: ['', Validators.required],
            billTo: ['', Validators.required],
            deliverTo: ['', Validators.required],
            orderNo: ['', Validators.required],
            orderDate: ['', Validators.required],
            shipDate: ['', Validators.required],
            dueDate: ['', Validators.required]

        });
    }
    
    ngAfterViewChecked(): void {
        if(this.child){
         this.childForm = this.child.cardForm;
        }
        if(this.addScreen){
            this.editForm = this.addScreen.addressForm;
        }
    }
    
    getCartItems() {
        this.store.select('cartItems').subscribe( cartItems => { 
            this.totalPrice = 0;
            this.cartItems = cartItems;
            this.cartItems.forEach(
                    item => { 
                        this.totalPrice = this.totalPrice + (parseFloat( item.itemHeader.itemDiscountedRate ) * item.itemQuantity);
                    }
            );
        });
    }
    
    executePayment() {
        let paymentInfo;

        switch(this.selectedPaymntOpt)
        {
            case 'newcard':
                    console.log('newcard');
                    paymentInfo = { "paymentOption":'card', "cardDetails": this.newCard};
                    break;
            case 'netbanking':
                    console.log('netbanking');
                    paymentInfo = { "paymentOption":'netbanking', "bankDetails": ''};
                    break;
            case 'cod':
                    console.log('COD');
                    paymentInfo = { "paymentOption":'COD'};
                    break;
            case 'wallet':
                    console.log('Wallet');
                    paymentInfo = { "paymentOption":'wallet'};
                    break;
            default:
                    console.log('DEFAULT');
                    paymentInfo = {  "paymentOption":'card', "cardDetails": this.cardList.find(x => x.lineNo === this.selectedPaymntOpt)};
                    break;
        }
        
        let order = { "token_id": this.userData.TOKEN_ID, "billAddress": this.selectedAddress, "orderedItems":this.cartItems, "paymentInfo": paymentInfo};
        
        console.log('-----order-----',order);
        
        this.placeOrder(order);
    }
    
    placeOrder(data) 
    {
        console.log( 'PlaceOrder dat[' + data + ']' );
        this.checkoutService.sendData(data, this.userData.TOKEN_ID).subscribe(
        result => {
           if(result.Response.status == 'Unauthorized')
           {
                this.unAuthorized=true;
           }
           else
            {
                 this.unAuthorized=false;
                 alert('Form sumited');
                 //this.store.dispatch(this.cartActions.resetCart());
                 this._location.back();
               
            }
            console.log( 'comp results[' + result.Response.results + ']status[' + result.Response.status + ']' );
            console.log( 'comp result.results.indexOf [' + result.Response.results.indexOf('{') + ']' );
           
        },
        error => {
            let errorMessage = <any>error;
            console.log( 'comp errorMessage[' + errorMessage + ']' );
        }
        );
    }
    
    saveAddress(){
        console.log('entered address',this.newAddress);
        this.onAddNew(this.newAddress);
        this.selectedAddress = this.newAddress;
        
        this.newAddress = new Address();
        
    }
    
    selectAddress(address){
        this.selectedAddress = address;
        setTimeout(() => {
            this.stepper.next();
        }, 500);
    }
    
    confirmOrder(){
        this.orderReviewed = true;
        setTimeout(() => {
            this.stepper.next();
        }, 500);
    }
    
    increment(item : ItemDetail) {
        item.itemQuantity++;
        let cartData = new Item;
        cartData.itemCode = item.itemCode;
        cartData.itemQuantity = item.itemQuantity;

        this.store.dispatch(this.cartActions.updateCart(cartData));
        this.openSnackBar( 'Quantity increased of ' + item.itemHeader.itemShDescr );
    }

    decrement(item : ItemDetail) {
        item.itemQuantity--;
        let cartData = new Item;
        cartData.itemCode = item.itemCode;
        cartData.itemQuantity = item.itemQuantity;
        this.store.dispatch(this.cartActions.updateCart(cartData));
        this.openSnackBar( 'Quantity decreased of ' + item.itemHeader.itemShDescr );
    }
    
    openSnackBar( message: string ) {
        this.snackBar.open( message, '', {
            duration: 2000,
        });
    }
    
    createUserData() {
         var userInfo = localStorage.getItem( 'userInfo' );
         if ( userInfo !== 'undefined' && userInfo !== null && userInfo !== 'null' ) 
        {
            this.userData = JSON.parse( userInfo );

            this.store.dispatch(this.addressActions.loadAddress());
            this.store.dispatch(this.cardActions.loadSavedCards());
        }
        else 
        {
            this.userData = null;
        }
        console.log( 'ECMHeaderComponent getUserInfo ::' + userInfo + ' \n this.userData :: ' + this.userData );
    }
    
    onAddNew(address: Address)
    {
        let lineNo = this.getMaxLineNo();
        //this.selectedAddress = lineNo;
        console.log( 'loadUser addressList >> ', lineNo);
        address.lineNo = lineNo+'';
        
        address.userName = address.firstName + " " + address.lastName;
        console.log('On Add new Click the userAddress name is ', address.userName);
        this.addressList.push( address );
        console.log('On Save Click From Add New ', address);
        this.store.dispatch(this.addressActions.addNewAdddress(address));
    }
    
    getMaxLineNo() : number {
        let maxLineNo = 0;
        
        for( let address of this.addressList){
            let addrLineNo : number = Number(address.lineNo);
            if(addrLineNo > maxLineNo){
                maxLineNo = addrLineNo;
            }
        }
        console.log('maxLineno--',maxLineNo);
        return maxLineNo + 1;
    }
    
     userAction() {
        //show overlay  with user-option
            if ( this.userData )
            {
                this.ecmPanel.open({ type: 'overlay', option: 'USER_OPT', top:'0px', left: '0px', width:'100%', height: '100%' });
            }
            else
            {
                this.ecmPanel.open({ type: 'overlay', option: 'SIGNIN_OPT', top:'0px', left: '0px', width:'100%', height: '100%' });
            }
        
            if ( this.userData )
            {
                //show sidepanel with user-option
                this.ecmPanel.open({ type: 'inplace', option: 'USER_OPT', top:'65px', left: '', right: '20px', width:'300px', height: '400px' });
            }
            else
            {
                //show overlay with sign-in-option
                this.ecmPanel.open({ type: 'overlay', option: 'SIGNIN_OPT', top:'100px', left: 'calc( 50% - 375px / 2 )', width:'375px', height: '535px' });
            }
              
     
     
   }
    
    ngDoCheck()
    {
         if( this.userData && !this.redirect)
        {
            console.log('stepper--',this.stepper._steps,this.stepper.selectedIndex);
            if(this.stepper._steps && this.stepper.selectedIndex == 0)
            {
                this.stepper.next();
                console.log('stepper-- ATFER SET',this.stepper , this.stepper.selectedIndex);
                this.redirect = true;
            }
        }
        //already not logged in
        else if(!this.userData){
            this.createUserData();
        }
    }
    
    onSelect(dataObj, field){
    console.log("dataObj in ecm checkout ",dataObj,dataObj.address);    
         this.addressObj = dataObj;
         this.address = dataObj.address;
        
        if(field == 'soldTo'){
            
            this.customerInformation.soldTo = dataObj;
        }
         if(field == 'billTo'){
            
            this.customerInformation.billTo = dataObj;
        }
         if(field == 'deliverTo'){
            
            this.customerInformation.deliverTo = dataObj;
        }
    }
    
    getSeparator( displayVal ){
        if( displayVal ) {
            return ',';
        }
        return '';
    }
    
    onClear(data){
    console.log("values in onDeSelect()---------");
        if(data == 'soldTo'){
            
             this.customerInformation.soldTo = '';
        }
         if(data == 'billTo'){
            
            this.customerInformation.billTo = ''; 
        }
        
         if(data == 'deliverTo'){
            
            this.customerInformation.deliverTo = '';
        }
    }
    
    submitForm(){
        console.log('submitted---',this.customerInformationFormGroup);
    }
}


