#include <memory>
#include <geners/IOException.hh>
#include <geners/arrayIO.hh>
#include "StOpt/core/grids/Mesh2DGeners.h"
#include "StOpt/core/grids/GridAdapt2DGeners.h"
#include "StOpt/core/utils/eigenGeners.h"

using namespace StOpt;
using namespace std;
using namespace gs;

bool GridAdapt2DGeners::write(ostream &p_of, const wrapped_base &p_base,
                                        const bool p_dumpId) const
{
    // If necessary, write out the class id
    const bool status = p_dumpId ? wrappedClassId().write(p_of) : true;

    // Write the object data out
    if (status)
    {
        const wrapped_type &w = dynamic_cast<const wrapped_type &>(p_base);
	write_pod(p_of, w.getXMin());
	write_pod(p_of, w.getXMax());
	write_pod(p_of, w.getYMin());
	write_pod(p_of, w.getYMax());
	write_item(p_of, w.getMeshes());
	write_item(p_of, w.getPoints());    
    }

    // Return "true" on success
    return status && !p_of.fail();
}

GridAdapt2D *GridAdapt2DGeners::read(const gs::ClassId &p_id, istream &p_in) const
{
    // Validate the class id. You might want to implement
    // class versioning here.
    wrappedClassId().ensureSameId(p_id);

    double xMin;
    read_pod(p_in,&xMin);
    double xMax;
    read_pod(p_in,&xMax);
    double yMin;
    read_pod(p_in,&yMin);
    double yMax;
    read_pod(p_in,&yMax);
    CPP11_auto_ptr< std::list< std::pair<std::shared_ptr< StOpt::Mesh2D>, std::shared_ptr<std::vector<Eigen::ArrayXi > > >> >  mesh =read_item<  std::list< std::pair<std::shared_ptr< StOpt::Mesh2D>, std::shared_ptr<std::vector<Eigen::ArrayXi > > >>>(p_in);	
    CPP11_auto_ptr<std::vector< Eigen::ArrayXd > >  points =read_item< std::vector< Eigen::ArrayXd >>(p_in);

    if (p_in.fail())    throw gs::IOReadFailure("In BIO::read: input stream failure"); // Read in the object data

    // Return the object
    return new GridAdapt2D(xMin,xMax, yMin, yMax,*mesh, *points);
}

const gs::ClassId &GridAdapt2DGeners::wrappedClassId()
{
    static const gs::ClassId wrapId(gs::ClassId::makeId<wrapped_type>());
    return wrapId;
}
