/*
 * Copyright 2023-2025 Hartmut Seichter and Contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */
#include "paradiso/context.hpp"
#include "paradiso/geometry.hpp"

#include "glad/glad.h"

namespace paradiso {

//
// Context::impl
//

struct Context::impl {

    RGBA clear_color_{};

    void set_viewport(const Rectangle& v) {
        glViewport(v.position.x, v.position.y, v.size.width, v.size.height);
    }

    const Rectangle viewport() {
        float _viewport[4] = {0, 0, 1, 1};
        glGetFloatv(GL_VIEWPORT, &_viewport[0]);

        return {.position = Point{.x = Point::value_type(_viewport[0]),
                                  .y = Point::value_type(_viewport[1])},
                .size = Size{.width = Size::value_type(_viewport[2]),
                             .height = Size::value_type(_viewport[3])}};
    }

    void clear() {
        glEnable(GL_CULL_FACE);
        glCullFace(GL_BACK);
        glFrontFace(GL_CCW);

        float rgba_f[4] = {0, 0, 0, 0};

        clear_color_.to_float(rgba_f);

        glClearColor(rgba_f[0], rgba_f[1], rgba_f[2], rgba_f[3]);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    }

    uint32_t get_error() const { return glGetError(); }
};

//
// Context
//

Context::Context() : impl_(std::make_unique<impl>()) {}

Context::~Context() = default;

Context& Context::set_blend() { return *this; }

Context& Context::set_viewport(const Rectangle& v) {
    impl_->set_viewport(v);
    return *this;
}

Rectangle Context::viewport() const { return impl_->viewport(); }

void Context::clear() { impl_->clear(); }

uint32_t Context::get_error() const { return impl_->get_error(); }

RGBA Context::clearcolor() const { return impl_->clear_color_; }

Context& Context::set_clearcolor(const RGBA& clear_color) {
    impl_->clear_color_ = clear_color;
    return *this;
}

} // namespace paradiso
