#include<stdlib.h>
#include"container.h"

container_t * create(int (*compare)(void *e1, void *e2), void * (*cpy)(void * e)){
    container_t *c = (container_t*)malloc(sizeof(container_t));
    dup_node_t *l = (dup_node_t*)malloc(sizeof(dup_node_t));
    l->ant = l;
    l->prox = l;
    l->elem = NULL;
    c->l = l;
    c->comp = compare;
    c->cpy = cpy;
    return c;
}

void _push_back(container_t *c, void *elem){
    dup_node_t *novo = (dup_node_t*)malloc(sizeof(dup_node_t));
    novo->elem = elem;
    novo->prox = c->l;
    novo->ant = c->l->ant;
    c->l->ant->prox = novo;
    c->l->ant = novo;
}

void visit(container_t * c, void (*visitor)(void * e)){
    for (dup_node_t *l = c->l->prox; l!=c->l; l=l->prox){
        visitor(l->elem);
    }
}

void visit_reverse(container_t * c, void (*visitor)(void * e)){
    for (dup_node_t *l = c->l->ant; l!=c->l; l=l->ant){
        visitor(l->elem);
    }
}

int search(container_t *c, void * elem){
    for (dup_node_t *l = c->l->prox;l!=c->l;l=l->prox){
        if (c->comp(l->elem,elem)==0){
            return 1;
        }
    }
    return 0;
}

dup_node_t * dup_node_copy(dup_node_t * node, dup_node_t * first, void * (cpy)(void * e)){

    dup_node_t * new_node = (dup_node_t*)malloc(sizeof(dup_node_t));
    dup_node_t * tail = NULL;

    new_node->prox = new_node;
    new_node->ant = new_node;
    new_node->elem = cpy(node->elem);

    if (node->prox != first){
        tail = dup_node_copy(node->prox,first,cpy);
        tail->ant->prox = new_node;
        new_node->prox = tail;
        new_node->ant = tail->ant;
        tail->ant = new_node;
    }

    return new_node;
}



container_t * duplicate(container_t *c){
    container_t * cp = (container_t*)malloc(sizeof(container_t));
    cp->l = dup_node_copy(c->l,c->l,c->cpy);
    cp->comp = c->comp;
    cp->cpy = c->cpy;

    return cp;

}


