/*******************************************************************************
 * Copyright (C) 2017-2026 Theodore Chang
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/

#include "B21.h"

#include <Domain/DomainBase.h>
#include <Element/Utility/B2DC.h>
#include <Section/Section.h>
#include <Toolbox/IntegrationPlan.h>

B21::IntegrationPoint::IntegrationPoint(const double C, const double W, unique_ptr<Section>&& M)
    : coor(C)
    , weight(W)
    , b_section(std::move(M))
    , strain_mat(2, 3, fill::zeros) {
    strain_mat(0, 0) = 1.;
    strain_mat(1, 1) = 3. * coor - 1.;
    strain_mat(1, 2) = 3. * coor + 1.;
}

B21::B21(const unsigned T, uvec&& N, const unsigned S, const unsigned P, const bool F)
    : SectionElement2D(T, b_node, b_dof, std::move(N), uvec{S}, F)
    , int_pt_num(P > 20 ? 20 : P)
    , b_trans(F ? std::make_unique<B2DC>() : std::make_unique<B2DL>()) {}

int B21::initialize(const shared_ptr<DomainBase>& D) {
    auto& section_proto = D->get<Section>(section_tag(0));

    b_trans->set_element_ptr(this);

    access::rw(length) = b_trans->get_length();

    const IntegrationPlan plan(1, int_pt_num, IntegrationPlan::Type::LOBATTO);

    mat local_stiffness(3, 3, fill::zeros);
    int_pt.clear();
    int_pt.reserve(int_pt_num);
    for(unsigned I{0}; I < int_pt_num; ++I) {
        int_pt.emplace_back(plan(I, 0), .5 * plan(I, 1), section_proto->unique_copy());
        int_pt[I].b_section->set_characteristic_length(int_pt[I].weight * length);
        local_stiffness += int_pt[I].strain_mat.t() * int_pt[I].b_section->get_initial_stiffness() * int_pt[I].strain_mat * int_pt[I].weight / length;
    }

    trial_stiffness = current_stiffness = initial_stiffness = b_trans->to_global_stiffness_mat(local_stiffness);

    if(const auto linear_density = section_proto->get_linear_density(); linear_density > 0.) trial_mass = current_mass = initial_mass = b_trans->to_global_mass_mat(linear_density);

    return SUANPAN_SUCCESS;
}

int B21::update_status() {
    b_trans->update_status();

    // const auto length = b_trans->get_length();

    const auto local_deformation = b_trans->to_local_vec(get_trial_displacement());

    mat local_stiffness(3, 3, fill::zeros);
    vec local_resistance(3, fill::zeros);
    for(const auto& I : int_pt) {
        if(SUANPAN_SUCCESS != I.b_section->update_trial_status(I.strain_mat * local_deformation / length)) return SUANPAN_FAIL;
        local_stiffness += I.strain_mat.t() * I.b_section->get_trial_stiffness() * I.strain_mat * I.weight / length;
        local_resistance += I.strain_mat.t() * I.b_section->get_trial_resistance() * I.weight;
    }

    trial_stiffness = b_trans->to_global_stiffness_mat(local_stiffness);
    trial_resistance = b_trans->to_global_vec(local_resistance);

    if(nlgeom) trial_geometry = b_trans->to_global_geometry_mat(local_resistance);

    return SUANPAN_SUCCESS;
}

int B21::commit_status() {
    b_trans->commit_status();

    auto code = 0;
    for(const auto& I : int_pt) code += I.b_section->commit_status();
    return code;
}

int B21::clear_status() {
    b_trans->clear_status();

    auto code = 0;
    for(const auto& I : int_pt) code += I.b_section->clear_status();
    return code;
}

int B21::reset_status() {
    b_trans->reset_status();

    auto code = 0;
    for(const auto& I : int_pt) code += I.b_section->reset_status();
    return code;
}

std::vector<vec> B21::record(const OutputType P) const {
    std::vector<vec> data;
    for(const auto& I : int_pt) suanpan::append_to(data, I.b_section->record(P));
    return data;
}

void B21::print() {
    suanpan_info("A classic 2D displacement based beam element using Hermite interpolation functions{}", nlgeom ? " and corotational formulation.\n" : ".\n");
    suanpan_info("The element connects nodes:", node_encoding);
    if(!is_initialized()) return;
    suanpan_info("Section:\n");
    auto J = 1;
    for(const auto& I : int_pt) {
        suanpan_info("IP {}: ", J++);
        I.b_section->print();
    }
}

#ifdef SUANPAN_VTK
#include <vtkLine.h>

vtkSmartPointer<vtkCell> B21::GetCell() const { return vtkSmartPointer<vtkLine>::New(); }

mat B21::GetData(const OutputType P) {
    const auto remap = [&](vec&& in) {
        mat data(6, b_node, fill::zeros);
        data.rows(uvec{0, 1, 5}) = reshape(in, b_dof, b_node);
        return data;
    };

    if(OutputType::A == P) return remap(get_current_acceleration());
    if(OutputType::V == P) return remap(get_current_velocity());
    if(OutputType::U == P) return remap(get_current_displacement());

    vec low, high;
    if(const auto t_data = int_pt.front().b_section->record(P); !t_data.empty()) low = t_data[0];
    if(const auto t_data = int_pt.back().b_section->record(P); !t_data.empty()) high = t_data[0];

    mat data(6, b_node);
    data.col(0) = low.resize(6);
    data.col(1) = high.resize(6);

    return data;
}

mat B21::GetDeformation(const double amplifier) { return get_coordinate(2).t() + amplifier * reshape(get_current_displacement(), b_dof, b_node).eval().head_rows(2); }

#endif
