#include <memory>
#include <geners/vectorIO.hh>
#include <geners/IOException.hh>
#include "StOpt/regression/LaplacianGridKernelRegressionGeners.h"
#include "StOpt/core/utils/eigenGeners.h"

using namespace StOpt;
using namespace std;

bool LaplacianGridKernelRegressionGeners::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);
        gs::write_pod(p_of, w.getBZeroDate());
        gs::write_item(p_of, w.getH());
        gs::write_pod(p_of, w.getCoefNbGridPoint());
        gs::write_pod(p_of, w.getBLinear());
        std::vector< std::shared_ptr<Eigen::ArrayXd> > z  =  w.getZ();
        int zSize = z.size();
        gs::write_pod(p_of, zSize);
        for (size_t id = 0; id < z.size(); ++id)
            gs::write_item(p_of, *z[id]);
    }

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

LaplacianGridKernelRegression *LaplacianGridKernelRegressionGeners::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);
    // Read in the object data
    bool bZeroDate ;
    gs::read_pod(p_in, &bZeroDate);
    unique_ptr< Eigen::ArrayXd>  h_ptr = gs::read_item<  Eigen::ArrayXd>(p_in);
    double coefNbGridPoint;
    gs::read_pod(p_in, &coefNbGridPoint);
    bool bLinear ;
    gs::read_pod(p_in, &bLinear);
    int nD ;
    gs::read_pod(p_in, &nD);
    std::vector< std::shared_ptr<Eigen::ArrayXd> >  z(nD);
    for (int id = 0; id < nD; ++id)
    {
        unique_ptr<Eigen::ArrayXd>  z_ptr = gs::read_item< Eigen::ArrayXd> (p_in);
        z[id] = std::move(z_ptr);
    }
    // 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 LaplacianGridKernelRegression(bZeroDate, *h_ptr, coefNbGridPoint, bLinear, z);
}

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

