#include <stdio.h>
#include <stddef.h>
#include <stdbool.h>
#include <string.h>
#include "node.h"

#define MAX_LEN 100

int contains(Node *head, char *data) {
    Node *current = head;
    while (current != NULL) {
        if (strcmp(current->data, data) == 0) {
            return true;
        }
        current = current->next_elem;
    }
    return false;
}

Node *search(Node **head, char *data) {
    Node *current = *head;

    // Only using this function here because the assignment asks for it. There is no reason to do this otherwise
    if (contains(current, data) == false) {
        return NULL;
    }

    while (current != NULL) {
        if (strcmp(current->data, data) == 0) {
            return current;
        }
        current = current->next_elem;
    }
    return NULL;
}


Node *searchForPrevious(Node **head, Node *current) {
    Node *previous = *head;
    while (previous != NULL) {
        if (previous->next_elem == current) {
            return previous;
        }
        previous = previous->next_elem;
    }
    return NULL;
}


void add(Node **head, char *data) {
    if (*head == NULL) {
        *head = createNode(data);
    } else {
        Node *current = *head;
        while (current->next_elem != NULL) {
            current = current->next_elem;
        }
        current->next_elem = createNode(data);
    }
}


void delete(Node **head, char *data) {
    if (*head == NULL) {
        return;
    }

    Node *result = search(head, data);
    if (result == NULL) {
        return;
    } else {
        Node *previous = searchForPrevious(head, result);
        if (previous == NULL) {
            // If the node to be deleted is the head
            Node *next = result->next_elem;
            destroyNode(result);
            *head = next;
        } else {
            // If the node to be deleted is not the head
            previous->next_elem = result->next_elem;
            destroyNode(result);
        }
        return;
    }

}


void findAndReplace(Node *head, char *data, char *newData) {
    Node *current = search(&head, data);
    if (current != NULL) {
        replaceData(current, newData);
    }
}

void printList(Node *head) {
    Node *current = head;
    while (current != NULL) {
        printf("%s\n", current->data);
        current = current->next_elem;
    }
}

int stop(Node **head) {
    Node *current = *head;
    while (current != NULL) {
        Node *next = current->next_elem;
        destroyNode(current);
        current = next;
    }
    return true;
}
