import { Component, OnInit, ViewChildren, QueryList } from '@angular/core';
import { Card } from './card-manager/card.model';
import { CardEditor } from './card-manager';
import { AppState } from '../ecm-store/reducers';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';
import { UserCardService } from './ecm-user-card.service';
import { SavedCardAction} from '../ecm-store/actions';


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

    cardList: Observable<Card[]>;
    @ViewChildren(CardEditor) cardEditors: QueryList<CardEditor>
    
    newCard: Card = new Card();
    
    userCard : Observable<Card[]>;
    
    constructor(private store: Store<AppState>, private cardActions: SavedCardAction){
        this.store.dispatch(this.cardActions.loadSavedCards());
    }   

    ngOnInit() {
        this.cardList = this.store.select('savedCards');
        
        localStorage.removeItem('editorId');
    }

    onSaveClick(card: Card)
    {
        console.log('On Save Click ', card);

        //TODO Call POST service (address)
        this.userCard = this.store.select('userCard');
        
        this.userCard.subscribe( CardData => { 
            CardData.forEach(
                    profileInfo => { 
                    }
            );
        });
    }

//    onAddNew(card: Card)
    onAddNew( newCard: Card )
    {
//        this.cardList.push( card );
        
        console.log('On Save Click From Add New--', newCard);
        let lineNo = this.getMaxLineNo();
        
        newCard.lineNo = lineNo + '';
        console.log('cardnumber--',newCard.acctNumber);
        
        this.store.dispatch(this.cardActions.addNewCardSuccess(newCard));
    }
    
    onDeleteCard(card: Card){
        
        console.log('delete card of user-card-component:', card);
        this.store.dispatch(this.cardActions.deleteCardSuccess(card));
    }

    onDiscard(editorId: string)
    {
        console.log('On Discard Click ', editorId);
        this.cardEditors.forEach(cardEditor => {
            if( editorId == cardEditor.editorId ) {
                console.log(cardEditor);
                cardEditor.cancel();
            }
        });
        //TODO Call POST service (address)
    }
    
    getMaxLineNo() : number {
        let maxLineNo = 0;
        
        this.cardList.forEach(cards => {
            cards.forEach( card => {
                if(Number(card.lineNo) > maxLineNo){
                    maxLineNo = Number(card.lineNo);
                }
            })
        });
        
        console.log('maxLineno--',maxLineNo);
        
        return maxLineNo + 1;
    }

}
