#include "arc/console/element.h"
#include "arc/console/view.h"

#include <stdlib.h>
#include <ncurses.h>

void ARC_ConsoleElement_Create(ARC_ConsoleElement **element, uint32_t type, uint8_t flags, ARC_String *string, ARC_Point pos, ARC_ConsoleElement_RenderFn renderFn){
    *element = (ARC_ConsoleElement *)malloc(sizeof(ARC_ConsoleElement));

    (*element)->type     = type;
    (*element)->flags    = flags;
    (*element)->string   = string;
    (*element)->pos      = pos;
    (*element)->renderFn = renderFn;
}

void ARC_ConsoleElement_Destroy(ARC_ConsoleElement *element){
    free(element);
}

void ARC_ConsoleElement_DefaultRenderFn(ARC_ConsoleView *view, ARC_ConsoleElement *element){
    if(element->flags & ARC_CONSOLE_ELEMENT_FLAG_SELECTED){
        ARC_ConsoleView_SetAttribute(view, ARC_CONSOLE_VIEW_ATTRIBUTE_REVERSE);
    }

    ARC_ConsoleView_RenderStringAt(view, element->string, element->pos);

    if(element->flags & ARC_CONSOLE_ELEMENT_FLAG_SELECTED){
        ARC_ConsoleView_SetAttribute(view, ARC_CONSOLE_VIEW_ATTRIBUTE_NONE);
    }
}

ARC_Bool ARC_ConsoleElement_IsSelectable(ARC_ConsoleElement *element){
    if(element->flags & ARC_CONSOLE_ELEMENT_FLAG_SELECTABLE){
        return ARC_True;
    }

    return ARC_False;
}

void ARC_ConsoleElement_SetSelected(ARC_ConsoleElement *element, ARC_Bool selected){
    if(selected){
        element->flags |= ARC_CONSOLE_ELEMENT_FLAG_SELECTED;
        return;
    }

    element->flags &= ~ARC_CONSOLE_ELEMENT_FLAG_SELECTED;
}

void ARC_NCursesElement_ToggleSelected(ARC_ConsoleElement *element){
    element->flags ^= ARC_CONSOLE_ELEMENT_FLAG_SELECTED;
}
