/********************************************************
 *  ██████╗  ██████╗████████╗██╗
 * ██╔════╝ ██╔════╝╚══██╔══╝██║
 * ██║  ███╗██║        ██║   ██║
 * ██║   ██║██║        ██║   ██║
 * ╚██████╔╝╚██████╗   ██║   ███████╗
 *  ╚═════╝  ╚═════╝   ╚═╝   ╚══════╝
 * Geophysical Computational Tools & Library (GCTL)
 *
 * Copyright (c) 2022  Yi Zhang (yizhang-geo@zju.edu.cn)
 *
 * GCTL is distributed under a dual licensing scheme. You can redistribute 
 * it and/or modify it under the terms of the GNU Lesser General Public 
 * License as published by the Free Software Foundation, either version 2 
 * of the License, or (at your option) any later version. You should have 
 * received a copy of the GNU Lesser General Public License along with this 
 * program. If not, see <http://www.gnu.org/licenses/>.
 * 
 * If the terms and conditions of the LGPL v.2. would prevent you from using 
 * the GCTL, please consider the option to obtain a commercial license for a 
 * fee. These licenses are offered by the GCTL's original author. As a rule, 
 * licenses are provided "as-is", unlimited in time for a one time fee. Please 
 * send corresponding requests to: yizhang-geo@zju.edu.cn. Please do not forget 
 * to include some description of your company and the realm of its activities. 
 * Also add information on how to contact you by electronic and paper mail.
 ******************************************************/

#include "gnuplot.h"

gctl::gnuplot::gnuplot(bool persist)
{
    _2buffer = false;
    pipe = popen(persist ? "gnuplot -persist" : "gnuplot", "w");
    if (!pipe) throw std::runtime_error("gnuplot pipe failed to open. Try install gnuplot first.");
}

gctl::gnuplot::~gnuplot()
{
    if (pipe) pclose(pipe);
}

void gctl::gnuplot::to_buffer()
{
    _2buffer = true;
    return;
}

void gctl::gnuplot::send(const std::string& cmd, bool next_block)
{
    if (!pipe) return;

    if (!_2buffer) fputs((cmd + "\n").c_str(), pipe);
    else
    {
        if (next_block) buffer.push_back(cmd + "\n\n");
        else buffer.push_back(cmd + "\n");
    }
    return;
}

void gctl::gnuplot::send_buffer(size_t repeat)
{
    if (!pipe) return;
    for (size_t i = 0; i < repeat; i++)
    {
        for (auto& line : buffer) fputs(line.c_str(), pipe);
        fputs("\n", pipe);
    }

    fflush(pipe);
    buffer.clear();
    return;
}

void gctl::gnuplot::send_data(std::string name, const std::vector<std::vector<double> > &data, bool next_block)
{
    if (!pipe) return;

    if (!_2buffer)
    {
        fputs((name + " << EOD\n").c_str(), pipe);

        int cnum = data.size();
        int dnum = data[0].size();
        std::string line;
        for (size_t i = 0; i < dnum; i++)
        {
            line = std::to_string(data[0][i]);
            for (size_t j = 1; j < cnum; j++)
            {
                line += " " + std::to_string(data[j][i]); 
            }
            fputs((line + "\n").c_str(), pipe);
        }

        fputs("EOD\n", pipe);
    }
    else
    {
        buffer.push_back(name + " << EOD\n");

        int cnum = data.size();
        int dnum = data[0].size();
        std::string line;
        for (size_t i = 0; i < dnum; i++)
        {
            line = std::to_string(data[0][i]);
            for (size_t j = 1; j < cnum; j++)
            {
                line += " " + std::to_string(data[j][i]); 
            }
            buffer.push_back(line + "\n");
        }

        buffer.push_back("EOD\n");
        if (next_block) buffer.push_back("\n");
    }
    return;
}

void gctl::gnuplot::save_buffer(const std::string& filename)
{
    time_t now = time(0);
	char* dt = ctime(&now);

    std::ofstream outfile;
    open_outfile(outfile, filename, ".gp");

    outfile << "# This script is saved by gctl::gnuplot on " << dt;
    outfile << "# For more information please connect yizhang-geo@zju.edu.cn" << std::endl;

    for (auto& line : buffer) outfile << line;
    outfile.close();
    return;
}