#include "iec_include.h"


LinkedList
LinkedList_getLastElement(LinkedList list)
{
    while (list->next != NULL) {
        list = list->next;
    }
    return list;
}
LinkedList
LinkedList_create()
{
    LinkedList newList;

    newList = (LinkedList) GLOBAL_MALLOC(sizeof(struct sLinkedList));
    newList->data = NULL;
    newList->next = NULL;

    return newList;
}
LinkedList
LinkedList_getNext(LinkedList list)
{
    return list->next;
}

void*
LinkedList_getData(LinkedList self)
{
    return self->data;
}

void
LinkedList_add(LinkedList list, void* data)
{
    LinkedList newElement = LinkedList_create();

    newElement->data = data;

    LinkedList listEnd = LinkedList_getLastElement(list);

    listEnd->next = newElement;
}
/**
 * Destroy list (free) without freeing the element data
 */
void
LinkedList_destroyStatic(LinkedList list)
{
    LinkedList nextElement = list;
    LinkedList currentElement;

    do {
        currentElement = nextElement;
        nextElement = currentElement->next;
        GLOBAL_FREEMEM(currentElement);
    }
    while (nextElement != NULL);
}

int
LinkedList_size(LinkedList list)
{
    LinkedList nextElement = list;
    int size = 0;

    while (nextElement->next != NULL) {
        nextElement = nextElement->next;
        size++;
    }

    return size;
}


LinkedList
LinkedList_get(LinkedList list, int index)
{
    LinkedList element = LinkedList_getNext(list);

    int i = 0;

    while (i < index) {
        element = LinkedList_getNext(element);

        if (element == NULL)
            return NULL;

        i++;
    }

    return element;
}

/**
 * Destroy list (free). Also frees element data with helper function.
 */
void
LinkedList_destroyDeep(LinkedList list, LinkedListValueDeleteFunction valueDeleteFunction)
{
    LinkedList nextElement = list;
    LinkedList currentElement;

    do {
        currentElement = nextElement;
        nextElement = currentElement->next;

        if (currentElement->data != NULL)
            valueDeleteFunction(currentElement->data);

        GLOBAL_FREEMEM(currentElement);
    }
    while (nextElement != NULL);
}
void
Memory_free(void* memb)
{
    GLOBAL_FREEMEM(memb);
}
void
LinkedList_destroy(LinkedList list)
{
    LinkedList_destroyDeep(list, Memory_free);
}