// Copyright (C) 2002 Neil Stevens <neil@qualityassistant.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
// THE AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
// AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// 
// Except as contained in this notice, the name(s) of the author(s) shall not be
// used in advertising or otherwise to promote the sale, use or other dealings
// in this Software without prior written authorization from the author(s).

#include "deck.h"
#include <cstdlib>

using namespace Deck;

int Deck::card(Suit s, Rank r)
{
	return (int)s + (int)r * 4;
}

int Deck::card(Special s)
{
	return (int)s;
}

Rank Deck::rank(int c)
{
	return (Rank)((c - suit(c)) / 4);
}

Suit Deck::suit(int c)
{
	return (Suit)(((c - 1) % 4) + 1);
}

Stack Deck::shuffle(bool joker, int deckCount)
{
	const int deckSize = joker ? 53 : 52;
	const int total = deckSize * deckCount;

	QMemArray<int> a(total);

	for(int i = 0; i < total; i++)
		a[i] = joker ? i % deckSize : i % deckSize + 1;

	for(int i = 0; i < total * 2; i++)
	{
		const int x = std::rand() % total;
		const int y = std::rand() % total;
		const int swap = a[x];
		a[x] = a[y];
		a[y] = swap;
	}

	return Stack(a);
}

int Deck::blackjackValue(int c)
{
	Rank r = rank(c);

	switch(r)
	{
	case Ace:
		return 11;
	case King:
	case Queen:
	case Jack:
	case Ten:
		return 10;
	case Nine:
		return 9;
	case Eight:
		return 8;
	case Seven:
		return 7;
	case Six:
		return 6;
	case Five:
		return 5;
	case Four:
		return 4;
	case Three:
		return 3;
	case Two:
		return 2;
	default:
		assert(0);
		return -1;
	}
}
