
#import "DrawPileDelegate.h"
#import <Solitaire/CardSet.h>


@implementation DrawPileDelegate

- (void) setDiscardCardPileView:theView
{
    discardCardPileView = theView; 
}

- (void) setDrawCardCount:(int)theCount
{
    maxIndex = theCount; 
}

- (void) clickedCard:(Card*)aCard in:(CardPileView*)drawCardPileView
{
    CardPile*   discardCardPile = [discardCardPileView cardPile];
    CardPile*   drawCardPile = [drawCardPileView cardPile];
    int   		drawIndex;
    Card*    	drawCard;

    // Two cases where aCard will be nil:
    //
    // (1) if Draw Pile is empty
    //
    // (2) if Draw Pile is NOT empty but user has clicked on an exposed
    //     area of the pile
    //
    // This is all pretty ugly because we want the draw-three option to
    // behave "nicely."
    
    if (aCard)
    {
        if (maxIndex == 1)
	{
	    if (drawCard = [drawCardPile dealTopCard])
	    {
            [drawCard flip];
            [discardCardPile addCard:drawCard];
	    }
	}
	else
	{
	    int extra;
	    
	    [recycleCardPile addPile:discardCardPile];
	    [discardCardPile empty];
	    
	    for (drawIndex = 0; drawIndex < maxIndex; drawIndex++)
	    {
	        if (drawCard = [drawCardPile dealTopCard])
              {
                [drawCard flip];
                [discardCardPile addCard:drawCard];
              }
	    }
	    extra = maxIndex - [discardCardPile cardCount];
	    for (drawIndex = 0; drawIndex < extra; drawIndex++)
	    {
            if (aCard = [recycleCardPile dealTopCard])
              {
                [discardCardPile insertCard:aCard at:CS_BOTTOM];
              }	    
	    }
	}
    }
    else if ([drawCardPile cardCount] == 0)
    {
        if (maxIndex == 1)
	{
	    [drawCardPile addPile:discardCardPile];
	    [discardCardPile empty];
	    [drawCardPile flip];
	}
	else
	{
	    [recycleCardPile addPile:discardCardPile];
	    [discardCardPile empty];
	    
	    [recycleCardPile flip];
	    [drawCardPile addPile:recycleCardPile];
	    [recycleCardPile empty];
	}
    }    
    
    [discardCardPileView display];
    [drawCardPileView display]; 
}

@end

