# include <Game/TagSet.h>
# include <iostream>
# include <cassert>
namespace Alice
{
  
  TagSet::TagSet()
    :
    standardTags(7)
  {
    setTag("Event", "?");
    setTag("Site", "?");
    setTag("Date", "????.??.??");
    setTag("Round", "?");
    setTag("White", "?");
    setTag("Black", "?");
    setTag("Result", "*");

    standardTags[0] = "Event";
    standardTags[1] = "Site";
    standardTags[2] = "Date";
    standardTags[3] = "Round";
    standardTags[4] = "White";
    standardTags[5] = "Black";
    standardTags[6] = "Result";
  };

  std::map<std::string, std::string>&
  TagSet::getTags()
  {
    return _tags;
  };

  const std::map<std::string, std::string>&
  TagSet::getTags() const
  {
    return _tags;
  };
  
  void
  TagSet::setTag( const std::string& name,
		  const std::string& value )
  {
    getTags()[ name ] = value;
  };

  void
  TagSet::readTag(std::istream& in)
  {
    char c;
    in >> c;
    assert(c == '[');
    std::string name;
    in >> name;
    in >> c;
    assert(c == '\"');
    std::string value;
    for (in.get(c); c != '\"'; in.get(c))
      value += c;
    in >> c;
    assert(c == ']');
    setTag(name, value);
  };
  
  void 
  TagSet::writeTag( std::ostream& out, const std::string& tag ) const
  {
    std::map<std::string, std::string>::const_iterator it = 
      getTags().find(tag);
    if (it == getTags().end())
      return;
    
    out<<"["<<it->first<<" \""<<it->second<<"\"]"<<std::endl;
  };
  
  void
  TagSet::write( std::ostream& out ) const
  {
    writeTag( out, "Event");
    writeTag( out, "Site");
    writeTag( out, "Date");
    writeTag( out, "Round");
    writeTag( out, "White");
    writeTag( out, "Black");
    writeTag( out, "Result");
    
    for (std::map<std::string, std::string>::const_iterator it = getTags().begin();
	 it != getTags().end();
	 ++ it)
      
      {
	if (std::find(standardTags.begin(), 
		      standardTags.end(),
		      it->first) == standardTags.end())
	  out<<"["<<it->first<<" \""<<it->second<<"\"]"<<std::endl;
      }
  };

  void
  TagSet::read( std::istream& in )
  {

    while (in)
      {
	char c;
	in >> c;
	in.putback(c);
	if (c != '[')
	  return;
	readTag(in);
      }
  };
  std::string
  TagSet::getTag(const std::string& name)
  {
    return getTags()[name];
  };

}; // namespace Alice
