/********************************************************
 *  ██████╗  ██████╗████████╗██╗
 * ██╔════╝ ██╔════╝╚══██╔══╝██║
 * ██║  ███╗██║        ██║   ██║
 * ██║   ██║██║        ██║   ██║
 * ╚██████╔╝╚██████╗   ██║   ███████╗
 *  ╚═════╝  ╚═════╝   ╚═╝   ╚══════╝
 * 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.
 ******************************************************/

#ifndef _GCTL_OFF_IO_H
#define _GCTL_OFF_IO_H

#include "../poly/triangle.h"
#include "file_io.h"

namespace gctl
{
    template <typename E, typename A>
    void read_off_acsii(std::string filename, array<vertex<point3dc, E>> &nodes, 
        array<type_triangle<A>> &facets)
    {
        std::ifstream infile;
        open_infile(infile, filename, ".off");

        std::string tmp_str;
        std::stringstream tmp_ss;

        // read head info
		do
		{
			std::getline(infile, tmp_str);
			if (tmp_str[0] != '#' && tmp_str != "OFF")
			{
                throw runtime_error("Invalid file format: " + tmp_str + ". From read_Geomview_off(...)");
			}
		}
		while (tmp_str[0] == '#');

        // read vertex and facet count
        int vert_num = -1, facet_num = -1, edge_num = -1;
        do
		{
			std::getline(infile, tmp_str);
			if (tmp_str[0] != '#')
			{
                str2ss(tmp_str, tmp_ss);
                tmp_ss >> vert_num >> facet_num >> edge_num;
                if (tmp_ss.fail() || vert_num <= 0 || facet_num <= 0 || edge_num < 0)
                {
                    throw runtime_error("Invalid file format: " + tmp_str + ". From read_Geomview_off(...)");
                }
			}
		}
		while (tmp_str[0] == '#');

        // read vertexes
        nodes.resize(vert_num);
        int i = 0;
        do
        {
            std::getline(infile, tmp_str);
			if (tmp_str[0] != '#')
			{
                str2ss(tmp_str, tmp_ss);
                tmp_ss >> nodes[i].x >> nodes[i].y >> nodes[i].z;
                nodes[i].id = i;
                if (tmp_ss.fail())
                {
                    throw runtime_error("Invalid file format: " + tmp_str + ". From read_Geomview_off(...)");
                }
                i++;
			}
        }
        while (i < vert_num);

        // read triangular facets
        facets.resize(facet_num);
        int vert_count, tmp_id[3];

        i = 0;
        do
        {
            std::getline(infile, tmp_str);
			if (tmp_str[0] != '#')
			{
                str2ss(tmp_str, tmp_ss);
                tmp_ss >> vert_count >> tmp_id[0] >> tmp_id[1] >> tmp_id[2];
                if (tmp_ss.fail() || vert_count != 3)
                {
                    throw runtime_error("Invalid file format: " + tmp_str + ". From read_Geomview_off(...)");
                }
                facets[i].set(nodes[tmp_id[0]], nodes[tmp_id[1]], nodes[tmp_id[2]], i);
                i++;
			}
        }
        while (i < facet_num);

        infile.close();
        return;
    }

    template <typename E, typename A>
    void save_off_ascii(std::string filename, const array<vertex<point3dc, E>> &nodes, 
        const array<type_triangle<A>> &facets)
    {
        std::ofstream outfile;
        open_outfile(outfile, filename, ".off");
        outfile << "OFF\n#vertex_number facet_number edge_number\n";
        outfile << nodes.size() << " " << facets.size() << " 0\n";
        outfile << "#vertex_list\n";
        for (int i = 0; i < nodes.size(); i++)
        {
            outfile << nodes[i].x << " " << nodes[i].y << " " << nodes[i].z << std::endl;
        }
        outfile << "#facet_list\n";
        outfile << "#vertex_number vertex_id1 vertex_id2 ...\n";
        for (int i = 0; i < facets.size(); i++)
        {
            outfile << "3 " << facets[i].vert[0]->id << " " << facets[i].vert[1]->id << " " << facets[i].vert[2]->id << std::endl;
        }
        outfile.close();
        return;
    }
};

#endif // _GCTL_OFF_IO_H