/********************************************************
 *  ██████╗  ██████╗████████╗██╗
 * ██╔════╝ ██╔════╝╚══██╔══╝██║
 * ██║  ███╗██║        ██║   ██║
 * ██║   ██║██║        ██║   ██║
 * ╚██████╔╝╚██████╗   ██║   ███████╗
 *  ╚═════╝  ╚═════╝   ╚═╝   ╚══════╝
 * Geophysical Computational Tools & Library (GCTL)
 *
 * Copyright (c) 2023  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 "gmt.h"

gctl::gmt::gmt()
{
    seesion_ok_ = false;
    GMT_API_ = nullptr;
    session_name_ = "";
    buffer_.clear();
    tmpfiles_.clear();
}

gctl::gmt::~gmt()
{
    if (GMT_API_ != nullptr)
    {
        GMT_Destroy_Session(GMT_API_);
        GMT_API_ = nullptr;
        seesion_ok_ = false;
        session_name_ = "";
    }

    if (!buffer_.empty()) buffer_.clear();
    if (!tmpfiles_.empty()) tmpfiles_.clear();
}

void gctl::gmt::begin_session(const std::string& pic_name, 
    const std::string& pic_type, const std::string& name)
{
    if (!buffer_.empty()) buffer_.clear();
    session_name_ = pic_name;

    GMT_API_ = GMT_Create_Session(name.c_str(), 2U, 0, nullptr);
    if (GMT_API_ == nullptr) throw std::runtime_error("[gctl::gmt] Fail to begin GMT session.");

    std::string cmd = pic_name + " " + pic_type;
    if (GMT_Call_Module(GMT_API_, "begin", GMT_MODULE_CMD, (char*) cmd.c_str()) != GMT_NOERROR)
        throw std::runtime_error("[gctl::gmt] Fail to execute GMT command.");
    else
    {
        cmd = "begin " + cmd;
        buffer_.push_back(cmd);
    }

    seesion_ok_ = true;
    return;
}

void gctl::gmt::end_session(bool show, bool clear_tmp)
{
    std::string cmd = "";
    if (show) cmd = "show";

    if (GMT_Call_Module(GMT_API_, "end", GMT_MODULE_CMD, (char*) cmd.c_str()) != GMT_NOERROR)
        throw std::runtime_error("[gctl::gmt] Fail to end GMT session.");
    else
    {
        cmd = "end " + cmd;
        buffer_.push_back(cmd);
    }

    if (clear_tmp)
    {
        for (auto& file : tmpfiles_) remove(file.c_str());
    }

    if (GMT_API_ != nullptr)
    {
        GMT_Destroy_Session(GMT_API_);
        GMT_API_ = nullptr;
    }

    seesion_ok_ = false;
    session_name_ = "";
    return;
}

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

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

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

    for (auto& line : buffer_) outfile << "gmt " << line << std::endl;
    outfile.close();

    buffer_.clear();
    return;
}

void gctl::gmt::call_module(const std::string& module, const std::string& cmd)
{
    if (GMT_Call_Module(GMT_API_, module.c_str(), GMT_MODULE_CMD, (char*) cmd.c_str()) != GMT_NOERROR)
        throw std::runtime_error("[gctl::gmt] Fail to execute GMT command.");
    else
    {
        std::string cmds = module + " " + cmd;
        buffer_.push_back(cmds);
    }
}

std::string gctl::gmt::create_grid(const array<double> &data, int xnum, int ynum, 
    double xmin, double dx, double ymin, double dy)
{
    if (seesion_ok_ == false)
        throw std::runtime_error("[gctl::gmt] GMT session is not started.");

    if (xnum*ynum != data.size())
        throw std::runtime_error("[gctl::gmt] The size of data does not match the grid size.");

    std::string gridname = session_name_ + "_grid_" + std::to_string(tmpfiles_.size() + 1) + ".nc";
    gctl::save_netcdf_grid(gridname, data, xnum, ynum, xmin, dx, ymin, dy);

    tmpfiles_.push_back(gridname);
    return gridname;
}