/********************************************************
 *  ██████╗  ██████╗████████╗██╗
 * ██╔════╝ ██╔════╝╚══██╔══╝██║
 * ██║  ███╗██║        ██║   ██║
 * ██║   ██║██║        ██║   ██║
 * ╚██████╔╝╚██████╗   ██║   ███████╗
 *  ╚═════╝  ╚═════╝   ╚═╝   ╚══════╝
 * 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_ENTITY_H
#define _GCTL_ENTITY_H

// system head file
#include "fstream"
// library head file
#include "../core/array.h"

namespace gctl
{
    // this variable is only valid in this source file to control
    // the output of a 2D or 3D entity.
    static char entity_delimiter = ' ';

    /**
     * @brief      Base structure of all physical entities
     *
     * @tparam     T     vertex type
     * @tparam     N     vertex number
     * @tparam     A     attribute type
     */
    template <typename T, int N, typename A = void>
    struct entity
    {
        int id; ///< entity index 
        T *vert[N]; ///< vertex pointer
        A *att; ///< attribute pointer
        bool self_host; ///< whether the vertice are created internally

        /**
         * Constructor
         */
        entity();

        /**
         * @brief      De-constructor
         */
        virtual ~entity();

        /**
         * @brief      Reset the structure to initial state
         */
        void reset();

        /**
         * @brief      Set delimiter for the output stream
         *
         * @param[in]  deli      delimiter
         */
        void set_delimiter(char deli);

        /**
         * @brief      Save binary data block to the output file stream
         *
         * @param      outfile     Output file stream
         */
        void out_binary(std::ofstream &outfile);
    };

    template <typename T, int N, typename A>
    entity<T, N, A>::entity()
    {
        id = -1;
        for (int i = 0; i < N; ++i)
        {
            vert[i] = nullptr;
        }
        att = nullptr;
        self_host = false;
        return;
    }

    template <typename T, int N, typename A>
    entity<T, N, A>::~entity()
    {
        if (self_host)
        {
            for (int i = 0; i < N; ++i)
            {
                delete vert[i];
                vert[i] = nullptr;
            }
            self_host = false;
        }
    }

    template <typename T, int N, typename A>
    void entity<T, N, A>::reset()
    {
        id = -1;
        if (self_host)
        {
            for (int i = 0; i < N; ++i)
            {
                delete vert[i];
                vert[i] = nullptr;
            }
        }
        else
        {
            for (int i = 0; i < N; ++i)
            {
                vert[i] = nullptr;
            }
        }

        att = nullptr;
        self_host = false;
        return;
    }

    template <typename T, int N, typename A>
    void entity<T, N, A>::set_delimiter(char deli)
    {
        entity_delimiter = deli;
        return;
    }

    template <typename T, int N, typename A>
    void entity<T, N, A>::out_binary(std::ofstream &outfile)
    {
        outfile.write((char*)&id, sizeof(int));

        int tmp_id = N;
        outfile.write((char*)&tmp_id, sizeof(int));
        for (int i = 0; i < N; ++i)
        {
            tmp_id = vert[i]->id;
            outfile.write((char*)&tmp_id, sizeof(int));
        }
        return;
    }

    template <typename T, int N, typename A>
    std::ostream &operator <<(std::ostream & os, const entity<T, N, A> &a)
    {
        os << a.id << entity_delimiter << N;
        for (int i = 0; i < N; ++i)
        {
            os << entity_delimiter << a.vert[i]->id;
        }
        return os;
    }

    template <typename T, int N, typename A>
    bool operator ==(const entity<T, N, A> &a, const entity<T, N, A> &b)
    {
        for (int i = 0; i < N; ++i)
        {
            if (a.vert[i] != b.vert[i])
            {
                return false;
            }
        }
        return true;
    }

    template <typename T, int N, typename A>
    bool operator !=(const entity<T, N, A> &a, const entity<T, N, A> &b)
    {
        for (int i = 0; i < N; ++i)
        {
            if (a.vert[i] != b.vert[i])
            {
                return true;
            }
        }
        return false;
    }

    template <typename T, typename V>
    void link_entity_attribute(T &in_ele, V *in_para)
    {
        in_ele.att = in_para;
        return;
    }

    template <typename T, typename V>
    void link_entity_attribute(array<T> &in_ele, const array<V> &in_para)
    {
        for (int i = 0; i < in_ele.size(); ++i)
        {
            in_ele[i].att = in_para.get(i);
        }
        return;
    }

    template <typename T, int N, typename A>
    void copy_entity(entity<T, N, A> *tar, const entity<T, N, A> *src)
    {
        if (src == nullptr || tar == nullptr)
        {
            throw gctl::runtime_error("Invalid pointer. From copy_entity(...)");
        }
        
        tar->id = src->id;
        tar->self_host = src->self_host;
        tar->att = src->att;

        for (size_t i = 0; i < N; i++)
        {
            tar->vert[i] = src->vert[i];
        }
        return;
    }

    template <typename T, int N, typename A, typename B>
    void copy_entity(entity<T, N, B> *tar, const entity<T, N, A> *src)
    {
        if (src == nullptr || tar == nullptr)
        {
            throw gctl::runtime_error("Invalid pointer. From copy_entity(...)");
        }
        
        tar->id = src->id;
        tar->self_host = src->self_host;
        // can't assign unknow types
        // tar->att = src->att;

        for (size_t i = 0; i < N; i++)
        {
            tar->vert[i] = src->vert[i];
        }
        return;
    }
};

#endif // _GCTL_ENTITY_H