#include "scrollbarnode.h"

#include <iostream>

#include "scene/meshnode.h"

#include "SparrowRenderer/mesh.h"
#include "SparrowRenderer/pbrmaterial.h"
#include "sparrowshell/sparrowshell.h"

ScrollBarNode::ScrollBarNode(glm::vec2 dimension, glm::vec3 bar_color):
    m_dimension(dimension),
    m_bar_position(glm::vec2(0)),
    m_bar_dimension(dimension),
    m_bar_color(bar_color),
    m_bar_color_updated(false),
    m_index_position(0),
    m_bar_size(0),
    m_total_size(0),
    m_bar_resized(false),
    m_bar_moved(false)
{
    Mesh* mesh = new Mesh("scrollbar");
    mesh->addRectangle2D(glm::vec2(0),m_dimension);
    PBRMaterial* mat = new PBRMaterial();
    mat->albedo = m_bar_color;
    mat->opacity = 0.8;
    mesh->setMaterial(mat);
    mesh->setDepth(SparrowShell::SHELL_DEPTH+1);
    mesh->initGL();
    m_bar = new MeshNode(mesh);
    addChild(m_bar);
}

void ScrollBarNode::computeTransform()
{
    m_bar->resetTransform();
    m_bar->moveTo2D(m_bar_position);
    m_bar->resize2D(m_dimension, m_bar_dimension);
}

void ScrollBarNode::update()
{
    GUINode::update();
    bool needTransformUpdate = false;
    if(m_bar_resized)
    {
        if(m_total_size > m_bar_size)
            m_bar_dimension.y = m_dimension.y * ((float)m_bar_size / (float)m_total_size);
        else
            m_bar_dimension.y = m_dimension.y;
        m_bar_resized = false;
        needTransformUpdate = true;
    }
    if(m_bar_moved)
    {
        if(m_total_size != 0)
            m_bar_position = glm::vec2(0,(m_dimension.y /m_total_size) * m_index_position);
        else
            m_bar_position = glm::vec2(0);
        m_bar_moved = false;
        needTransformUpdate = true;
    }
    if(m_bar_color_updated)
    {
        PBRMaterial* mat = (PBRMaterial*) m_bar->getGeometryNode()->mesh->getMaterial();
        mat->albedo = m_bar_color;
        m_bar_color_updated = false;
    }
    if(needTransformUpdate)
        computeTransform();
}

glm::vec2 ScrollBarNode::getDimension()
{
    return m_dimension;
}

void ScrollBarNode::setBarColor(glm::vec3 color)
{
    m_bar_color = color;
    m_bar_color_updated = true;
}

void ScrollBarNode::setIndex(int index){
    m_index_position = index;
    m_bar_moved = true;
}

void ScrollBarNode::setBarSize(int size){
    m_bar_size = size;
    m_bar_resized = true;
}

void ScrollBarNode::setSize(int total){
    m_total_size = total;
    m_bar_resized = true;
}
