#include "shellbuffer.h"
#include "scene/meshnode.h"
#include "scene/textnode.h"
#include "sparrowshell/sparrowshell.h"
#include "tools/utils.h"
#include <iostream>

void ShellBuffer::update()
{
    TextNode* tnode;
    glm::vec2 text_pos(0,0);

    SparrowShell* shell = dynamic_cast<SparrowShell*>(m_parent);
    if(shell->isEnabled() && m_buffer_modified)
    {
        for(unsigned int i = 0; i< size();i++)
        {
            tnode = (TextNode*) (*this)[i];
            if (i >= m_index && i < m_index+SparrowShell::BUFFER_DISPLAYED_LINES)
            {
                tnode->moveTo2D(text_pos);
                tnode->setVisible(true);
                text_pos.y += m_font_size;
            }
            else
                tnode->setVisible(false);
        }
        m_buffer_modified = false;
    }
    GUINode::update();
}

void ShellBuffer::push(TextNode* tnode){
    if(tnode != nullptr)
    {
        if(m_scene != nullptr)
            tnode->setSceneTree(m_scene);

        if (m_children.size() >= m_max_size){
            (m_children[m_zero_offset])->setVisible(false);
            m_children[m_zero_offset++] = tnode;
            m_zero_offset %= m_max_size;
        }else
            m_children.push_back(tnode);
        tnode->m_parent = this;
        tnode->setParentTransform(m_transform);
        tnode->setParentVisible(isVisible());
        m_buffer_modified = true;
    }
}

glm::vec2 ShellBuffer::getDimension(){
    return glm::vec2(getEngine().getWindow()->getSize().x - SparrowShell::SCROLLBAR_PIXEL_WIDTH,
                     SparrowShell::BUFFER_DISPLAYED_LINES * SparrowShell::DEFAULT_FONT_SIZE);
}

void ShellBuffer::clear(){
    for(auto it = m_children.begin(); it != m_children.end();){
        TextNode* child = (TextNode*) *it;
        m_scene->removeFromIndex(child);
        it = m_children.erase(it);
        delete child;
    }
    m_index = 0;
}
