/* -*- indent-tabs-mode: nil; -*-
 *
 * This file is part of the Mango recipe management distribution.
 * Copyright (c) 2000-2003, Roland Jesse
 * All rights reserved.
 *
 * For license and copyright information see the file COPYRIGHT or 
 * <http://www.opensource.org/licenses/bsd-license.html>.
 *
 * $Id: MangoExporter.cpp,v 1.6 2003/05/11 14:46:11 rjesse Exp $
 */

#include "MangoExporter.h"
#include "Ingredient.h"
#include "Menu.h"
#include "RecipeModel.h"
#include "resources.h"
#include <qfile.h>

MangoExporter::MangoExporter( RecipeModel* cookbook)
   : Exporter( cookbook)
{
}

/*!
  A single recipe is always exported as a new cookbook containing
  only this recipe.
  \param r is non-const as its internal cookbook list is modified
*/
MangoExporter::MangoExporter( Recipe& r)
   : Exporter( r)
{
   RecipeModel* cb = new RecipeModel( r.title());
   *cb += r;
   setCookbook( cb);
}

MangoExporter::~MangoExporter()
{
}

QString
MangoExporter::getExtensions()
{
   return QString( tr( "Mango recipes (*.mango)"));
}

void
MangoExporter::apply()
   throw( Error)
{
   if (m_fname.isEmpty())
      throw Error( tr( "RecipeMLExporter: no file name set"));

   QFile file( m_fname);
   if (! file.open( IO_WriteOnly)) {
      QString str;
      QTextOStream( &str)
         << "Could not open file " << m_fname << " for writing.";
      throw Error( str);
   }
   m_stream.setDevice( &file);
   m_stream.setVersion( 4);     // Compatible to Qt 3.x or above

   createCookbookHeader();
   createRecipes();
}

/*!
  \see file resources.h for version history information.
*/
void
MangoExporter::createCookbookHeader()
{
   m_stream << QString( "Mango Cookbook");
   m_stream << m_stream.version();
   m_stream << (Q_INT32)MANGO_FILE_VERSION_CURRENT;
   m_stream << m_cookbook->getName();
}

/*!
  Serialise all recipes.
*/
void
MangoExporter::createRecipes()
{
   RecipeModel::RecipeList recipeList = m_cookbook->getRecipeList();
   // number of recipes:
   m_stream << (Q_UINT32) recipeList.size();

   // all recipes, one by one:
   RecipeModel::RecipeList::const_iterator rIt;
   for (rIt = recipeList.begin(); rIt != recipeList.end(); rIt++) {
      m_recipe = *rIt;
      m_stream << m_recipe;
   }

   // New since Mango's format version 2: Menus.
   RecipeModel::MenuList menuList = m_cookbook->getMenuList();
   m_stream << (Q_UINT32) menuList.size();   // number of menus
   RecipeModel::MenuList::const_iterator mIt;
   for (mIt = menuList.begin(); mIt != menuList.end(); mIt++) {
      Menu m( *mIt);
      m_stream << m;
   }
}

/*!
  Not used as Recipe knows itself how to output to a QDataStream.
*/
void
MangoExporter::createRecipeHeader()
{
}

/*!
  Not used as Recipe knows itself how to output to a QDataStream.
*/
void
MangoExporter::createRecipeBody()
{
}
