#include "list.h"
#include "stdio.h"

/* Log Management */
#define FATAL_LIST
#define ERROR_LIST
//#define INFO_LIST
//#define WARN_LIST
//#define DEBUG_LIST

T_List_ptr L_createlist() {
  return NULL;
};

T_List_ptr L_empty(T_List_ptr list) {
  while (list != NULL)
    list = L_remove(list);
  return NULL;
};

T_List_ptr L_insertInOrder(T_List_ptr list, T_Transaction * trans) {
  T_List_ptr newItem;
  T_List_ptr current;
  T_List_ptr previous;

  // create the new list element
  newItem = (T_List_ptr)malloc(sizeof(struct T_List));
  newItem->item = trans;
  // find the place to insert the transaction
  previous = NULL;
  current = list;
  while ((current != NULL) && isSmallerId(current->item->transaction.tid, trans->transaction.tid)) {
    previous = current;
    current = current->next;
  };
  // insert transaction
  newItem->next = current;
  if (previous != NULL) {
    previous->next = newItem;
  } else {
    list = newItem;
  }
  return list;
};

T_List_ptr L_remove(T_List_ptr list) {
  T_List_ptr aux;

  if (list == NULL) {
#ifdef ERROR_LIST
    printf("Error trying to remove from empty list\n");
#endif

  }
  aux = list;
  list = list->next;
  free(aux);
  return list;
};

T_List_ptr L_removeByID(T_List_ptr list, T_Tid tid) {
  T_List_ptr current;
  T_List_ptr previous;

  previous = NULL;
  current = list;
  while ((current != NULL) && !isEqualId(current->item->transaction.tid, tid)) {
    previous = current;
    current = current->next;
  };
  if (current == NULL)
#ifdef ERROR_LIST
    printf("Error trying to remove an id that is not in the list\n");
#endif

  if (previous == NULL) {
    list = current->next;
  } else {
    previous->next = current->next;
  };
  free(current);
  return list;
};

T_Transaction * L_getFirst(T_List_ptr list) {
  if (list == NULL) {
#ifdef FATAL_LIST
    printf("Error calling first on an empty list (FATAL ERROR)\n");
#endif
    exit(1);
  }
  return list->item;
};

T_Transaction * L_getTransaction(T_List_ptr list, T_Tid tid) {
  T_List_ptr current;
  current = list;

  while ((current != NULL) && !isEqualId(current->item->transaction.tid, tid)) {
    current = current->next;
  };
  if (current == NULL) {
    //printf("Error the transaction %d is not in the list\n", tid);
    //exit(1);
    return NULL;
  } else {
    return current->item;
  }
};
