#include <geners/IOException.hh>
#include "geners/GenericIO.hh"
#include "StOpt/regression/SparseRegressionGeners.h"
#include "StOpt/core/utils/eigenGeners.h"
#include "StOpt/core/grids/SparseSpaceGridNoBoundGeners.h"

using namespace StOpt;

bool SparseRegressionGeners::write(std::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);
        gs::write_pod(p_of, w.getBZeroDate());
        gs::write_item(p_of, w.getMesh());
        gs::write_item(p_of, w.getSpGrid());
        gs::write_item(p_of, w.getMeanX());
        gs::write_item(p_of, w.getEtypX());
        gs::write_item(p_of, w.getSvdMatrix());
    }

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

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

    // Read in the object data
    bool bZeroDate = 0;
    gs::read_pod(p_in, &bZeroDate);
    CPP11_auto_ptr< std::vector< std::vector< double> > > mesh = gs::read_item<  std::vector< std::vector< double> > >(p_in);
    CPP11_auto_ptr< StOpt::SparseSpaceGridNoBound > spGrid = gs::read_item< StOpt::SparseSpaceGridNoBound >(p_in);
    std::unique_ptr< Eigen::ArrayXd> meanX = gs::read_item<  Eigen::ArrayXd>(p_in);
    std::unique_ptr< Eigen::ArrayXd> etypX = gs::read_item<  Eigen::ArrayXd>(p_in);
    std::unique_ptr< Eigen::MatrixXd> svdMatrix = gs::read_item<  Eigen::MatrixXd>(p_in);

    // Check that the stream is in a valid state
    if (p_in.fail()) throw gs::IOReadFailure("In BIO::read: input stream failure");

    // Return the object
    return new SparseRegression(bZeroDate, std::move(spGrid), *mesh, *meanX, *etypX, *svdMatrix);
}

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

