#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){
    int fault = 0;
    if (animalArray == NULL || animalPtr == NULL || numberOfAnimalsPresent >= animalArrayLength) {
        fault = -1; // Invalid
    } else {
        animalArray[numberOfAnimalsPresent] = *animalPtr;
        ++numberOfAnimalsPresent;
    }
    *newNumberOfAnimalsPresent = numberOfAnimalsPresent;
    return fault;
}

int removeAnimal(int animalId, Animal* animalArray, size_t numberOfAnimalsPresent, size_t* newNumberOfAnimalsPresent){
    int fault = -1;
    if (animalArray == NULL || numberOfAnimalsPresent == 0) {
        fault = -1; // Invalid
    } else {
        for (size_t i = 0; i < numberOfAnimalsPresent; ++i) {
            if (animalArray[i].Id == animalId) {
                // move the array elements to the left to remove the animal
                for (size_t j = i; j < numberOfAnimalsPresent - 1; ++j) {
                    animalArray[j] = animalArray[j + 1];
                }
                --numberOfAnimalsPresent;
                fault = 0;
                break;
            }
        }
    }
    *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;
}
