#include "administration.h"

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "animal.h"

int addAnimal(const Animal* animalPtr, Animal* animalArray, size_t animalArrayLength, size_t numberOfAnimalsPresent, size_t* newNumberOfAnimalsPresent){
    if (animalArray == NULL || animalPtr == NULL || newNumberOfAnimalsPresent == NULL || numberOfAnimalsPresent >= animalArrayLength) {
        return -1; // Invalid
    }
    animalArray[numberOfAnimalsPresent] = *animalPtr;
    *newNumberOfAnimalsPresent = numberOfAnimalsPresent + 1;
    return 0;
}

int removeAnimal(int animalId, Animal* animalArray, size_t numberOfAnimalsPresent, size_t* newNumberOfAnimalsPresent){
    int fault = -1;
    size_t removedCount = 0;
    
    if (animalArray == NULL || numberOfAnimalsPresent == 0) {
        fault = -1; // Invalid
    } else {
        size_t writeIndex = 0;
        
        // Copy only animals that don't match the ID
        for (size_t readIndex = 0; readIndex < numberOfAnimalsPresent; ++readIndex) {
            if (animalArray[readIndex].Id != animalId) {
                if (writeIndex != readIndex) {
                    animalArray[writeIndex] = animalArray[readIndex];
                }
                writeIndex++;
            } else {
                removedCount++;
                fault = 0;  // Found some animal(s) to remove
            }
        }
        // Update the number of animals present
        numberOfAnimalsPresent -= removedCount;
    }
    
    *newNumberOfAnimalsPresent = numberOfAnimalsPresent;
    return fault;
}

int findAnimalById(int animalId, const Animal* animalArray, size_t numberOfAnimalsPresent, Animal* foundAnimal) {
    int fault = -1;
    if (animalArray == NULL || numberOfAnimalsPresent == 0 || foundAnimal == NULL) {
        fault = -1;
    } else {
        for (size_t i = 0; i < numberOfAnimalsPresent; i++) {
            if (animalArray[i].Id == animalId) {
                *foundAnimal = animalArray[i];
                fault = 0;
                break;  // Exit loop after finding the animal
            }
        }
        if (fault == -1) {  // Only zero out if animal wasn't found
            memset(foundAnimal, 0, sizeof(Animal));
        }
    }
    return fault;
}
