#
# Import/export definitions for Apprentice
# ======================================
#

apprentice.set_map=(,);
apprentice.set_map{"CHK"}="CK";

#
# IsApprenticeDeck(file content) - Return 1 if the file is a Apprentice-deck.
#
def IsApprenticeDeck
{
  push(i);
  i=0;
  while(i<length(ARG))
  {
    if(left(ARG[i],2)=="//" || left(ARG[i],3)=="SB:")
    {
      return(1);
      i=length(ARG);
    }
    i=i+1;
  }
  i=pop();
}

#
# ImportApprenticeDeck(file content) - Importer for Apprentice-deck.
#
def ImportApprenticeDeck
{
  ImportReaderLineByLine(ARG,"SlashComments","TrimSpaces","None","ApprenticeFormatParser");
}

#
# ApprenticeFormatParser(text line) - Text line parser for Apprentice-deck.
#
def ApprenticeFormatParser
{
  push(l);
  push(c);
  push(s);
  push(i);
  l=ARG;

  if(left(l,3)=="SB:")
  {
    import.part="sideboard";
    l=trim(substr(l,3));
  }
  else
    import.part="deck";

  l=LineSplitFirstSpace(l);
  c=trim(last(l));
  if(first(c)=="[")
  {
    i=find("]",c);
    if(i!=NULL)
    {
      s=uc(substr(c,1,i-1));
      if(has_entry(s,apprentice.set_map))
        s=apprentice.set_map{s};

      if(substr(c,length(c)-3,1)=="(" && last(c)==")")
         c=trim(left(c,length(c)-3));

      c=trim(substr(c,i+1))+" ("+s+")";
    }
  }

  c=RecognizeCard(c);
  if(c==NULL)
    ImportErrorAdd(ARG);
  else
    ImportAdd(toint(first(l)),c);

  i=pop();
  s=pop();
  c=pop();
  l=pop();
}

#
# ExportApprenticeDeck(deck name,deck strucutre) - Convert a deck to
#   the list of lines of the Apprentice file.
#
def ExportApprenticeDeck
{
  push(x);
  x=(
   ("//NAME: "+ARG[0],)+
   ("","// Lands",)+forall('"        "+#',CountNamePairs(SelectByAttr(ARG[1]{"deck"},"type","Land")))+
   ("","// Creatures",)+forall('"        "+#',CountNamePairs(SelectByAttr(ARG[1]{"deck"},"type","Creature")))+
   ("","// Spells",)+forall('"        "+#',CountNamePairs(InverseSelectByAttr(InverseSelectByAttr(ARG[1]{"deck"},"type","Creature"),"type","Land")))
  );
  if(has_entry("sideboard",ARG[1]))
    x=x+("","// Sideboard")+forall('"SB:  "+#',CountNamePairs(ARG[1]{"sideboard"}));

  return(x);

  x=pop();
}

#
# ApprenticeFormatSuffix() - Return filename suffix .dec for Apprentice-format.
#
def ApprenticeFormatSuffix
{
  return(".dec");
}
