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

using namespace StOpt;
using namespace std;

bool ContinuationValueGeners::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);
        int isizeRows = w.getValues().rows();
        int isizeCols = w.getValues().cols();
        gs::write_pod(p_of, isizeRows);
        gs::write_pod(p_of, isizeCols);
        gs::write_pod_array(p_of, w.getValues().data(), isizeRows * isizeCols);
        std::shared_ptr< StOpt::SpaceGrid > ptrGrid = w.getGrid();
        bool bSharedPtr = (ptrGrid ? true : false);
        gs::write_pod(p_of, bSharedPtr);
        if (bSharedPtr)
            gs::write_item(p_of, *w.getGrid());
        gs::write_item(p_of, *w.getCondExp());
    }

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

ContinuationValue *ContinuationValueGeners::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
    int isizeRows = 0;
    gs::read_pod(p_in, &isizeRows);
    int isizeCols = 0;
    gs::read_pod(p_in, &isizeCols);
    int isizeLoc = isizeRows * isizeCols;
    Eigen::ArrayXXd values(isizeRows, isizeCols);
    gs::read_pod_array(p_in, values.data(), isizeLoc);
    bool bSharedPtr ;
    gs::read_pod(p_in, &bSharedPtr);
    CPP11_auto_ptr<StOpt::SpaceGrid> pgrid ;
    if (bSharedPtr)
        pgrid  = gs::read_item<StOpt::SpaceGrid>(p_in);
    std::shared_ptr<StOpt::SpaceGrid > pgridShared(std::move(pgrid));
    CPP11_auto_ptr<StOpt::BaseRegression> pcond  = gs::read_item<StOpt::BaseRegression>(p_in);
    std::shared_ptr<StOpt::BaseRegression> pcondShared(std::move(pcond));
    // 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
    StOpt::ContinuationValue *ptr = new StOpt::ContinuationValue();
    ptr->loadForSimulation(pgridShared, pcondShared, values);
    return ptr;
}

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

