/* This file is part of cardwords
   (c) 1998 1999 Tobias Peters
   
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*/

// cardwords_pile.cc

#include "cardwords_pile.hh"
#include <stdlib.h>
#include <time.h>
#include <strstream.h>
#include "cardwords_exceptions.hh"

// Selects a randomly chosen card:
CardWords_Card *
CardWords_Pile::produce_card(void) const
{
  if (size() == 0) {
    return 0;
  }
  size_t number = rand() % size();
  const_iterator iter = begin();
  while (number > 0) {
    iter++;
    number--;
    assert (iter != end());
  }
  return *iter;
}

// The constructor takes one argument: An istream where it
// reads the card specs from.
// The total number of cards in the game is also expected (first)
// in the istream.
// The necessary cards will be allocated on the heap.


inline static int read_int(istream & istream)
{
  int i;
  istream >> i;
  if (istream.bad())
    throw CardWords_XBadInput(gettext("size of pile for the constructor"),
			    gettext("number"));
  return i;
}

CardWords_Pile::CardWords_Pile(istream & cardSpecs)
  : CardWords_CardContainer1Dim(read_int (cardSpecs))
{
  cardCount = total_places();
  assert (cardCount >= 2); // Minimale Wortlänge
  for (size_t index = 0; index < cardCount; index++) {
    add_card(new CardWords_Card (cardSpecs));
  }

  // Write the actual contents of this container back to a string,
  // this string can serve as a cardSpecs saving, because all cards
  // are now here in the pile.
  ostrstream stringStream;
  stringStream << *this << ends;
  stringStream.freeze(true);
  this->cardSpecs = stringStream.str();
  stringStream.freeze(false);
  
  // initialize the random number generator
  srand(time(NULL));
}

// Since the pile creates the cards, here is the place to ask what
// cards are in the game
// The format of this output is suitable to act as the input for the
// constructor:
void
CardWords_Pile::print_cardSpecs (ostream & ostream) const
{
  ostream << cardSpecs << endl;
}

CardWords_Pile::~CardWords_Pile()
{}
