#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){
    size_t removedCount = 0;
    
    if (animalArray == NULL || numberOfAnimalsPresent == 0) {
        return -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++;
            }
        }
    }
    *newNumberOfAnimalsPresent = (numberOfAnimalsPresent - removedCount);
    return removedCount;
}

int findAnimalById(int animalId, const Animal* animalArray, size_t numberOfAnimalsPresent, Animal* foundAnimal) {
    if (animalArray == NULL || foundAnimal == NULL) return -1; // Invalid input
    
    for (size_t i = 0; i < numberOfAnimalsPresent; i++) {
        if (animalArray[i].Id == animalId) {
            *foundAnimal = animalArray[i];
            return 0;
        }
    }
    return 0;
}