
#import "DrawPileDelegate.h"
#import "../Solitaire/CardSet.subproj/cardset.h"


@implementation DrawPileDelegate

- setDiscardCardPileView:theView
{
    discardCardPileView = theView;
    return self;
}

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

- clickedCard:aCard in:drawCardPileView
{
    id    discardCardPile = [discardCardPileView cardPile];
    id    drawCardPile = [drawCardPileView cardPile];
    int   drawIndex;
    id    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 cardAt:CS_TOP])
	    {
	        [drawCardPile removeCard:drawCard];
		[drawCard flip];
		[discardCardPile addCard:drawCard];
	    }
	}
	else
	{
	    int extra;
	    
	    [recycleCardPile addPile:discardCardPile];
	    [discardCardPile empty];
	    
	    for (drawIndex = 0; drawIndex < maxIndex; drawIndex++)
	    {
	        if (drawCard = [drawCardPile cardAt:CS_TOP])
		{
		    [drawCardPile removeCard:drawCard];
		    [drawCard flip];
		    [discardCardPile addCard:drawCard];
		}
	    }
	    extra = maxIndex - [discardCardPile cardCount];
	    for (drawIndex = 0; drawIndex < extra; drawIndex++)
	    {
		if (aCard = [recycleCardPile cardAt:CS_TOP])
		{
		    [recycleCardPile removeCard:aCard];
		    [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];

    return self;
}

@end
