#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "a_station.h"

// Функція для створення порожньої станції
struct station* create_station() {
    struct station* new_station = (struct station*)malloc(sizeof(struct station));
    if (new_station == NULL) {
        return NULL;
    }
    new_station->tracks = (struct car**)malloc(sizeof(struct car*) * STATION_SIZE);
    if (new_station->tracks == NULL) {
        free(new_station);
        return NULL;
    }
    for (int i = 0; i < STATION_SIZE; i++) {
        new_station->tracks[i] = NULL;
    }
    new_station->track_count = STATION_SIZE;
    return new_station;
}

// Функція для звільнення пам'яті, зайнятої станцією
void destroy_station(struct station* station) {
    if (station != NULL) {
        for (int i = 0; i < station->track_count; i++) {
            struct car* current = station->tracks[i];
            while (current != NULL) {
                struct car* next = current->next;
                free(current);
                current = next;
            }
        }
        free(station->tracks);
        free(station);
    }
}

// Хеш-функція для вибору треку
int select_track(struct station* station, const char* target) {
    unsigned int hash = 0;
    for (int i = 0; target[i] != '\0'; i++) {
        hash = (hash * 31 + target[i]) % station->track_count;
    }
    return hash;
}

// Додавання або збільшення запису про кількість пасажирів
void add_target_capacity(struct station* station, const char* target, int capacity) {
    int track_index = select_track(station, target);
    struct car* current = station->tracks[track_index];

    while (current != NULL) {
        if (strcmp(current->value, target) == 0) {
            current->capacity += capacity;
            return;
        }
        current = current->next;
    }

    // Створення нового запису, якщо цільова станція не знайдена
    struct car* new_car = (struct car*)malloc(sizeof(struct car));
    if (new_car == NULL) {
        return;
    }
    strncpy(new_car->value, target, TARGET_SIZE - 1);
    new_car->value[TARGET_SIZE - 1] = '\0';
    new_car->capacity = capacity;
    new_car->next = station->tracks[track_index];
    station->tracks[track_index] = new_car;
}

// Отримання запису про кількість пасажирів для цільової станції
int get_target_capacity(struct station* station, const char* target) {
    int track_index = select_track(station, target);
    struct car* current = station->tracks[track_index];

    while (current != NULL) {
        if (strcmp(current->value, target) == 0) {
            return current->capacity;
        }
        current = current->next;
    }
    return 0;
}

// Підрахунок кількості цільових станцій
int count_targets(struct station* station) {
    int target_count = 0;
    for (int i = 0; i < station->track_count; i++) {
        struct car* current = station->tracks[i];
        while (current != NULL) {
            target_count++;
            current = current->next;
        }
    }
    return target_count;
}

// Підрахунок загальної кількості пасажирів на всі станції
int count_capacity(struct station* station) {
    int total_capacity = 0;
    for (int i = 0; i < station->track_count; i++) {
        struct car* current = station->tracks[i];
        while (current != NULL) {
            total_capacity += current->capacity;
            current = current->next;
        }
    }
    return total_capacity;
}

// Функція для завантаження бази даних з текстового файлу
void save_to_file(struct station* moja_stanica) {
    FILE *file = fopen("data.txt", "w");
    if (file == NULL) {
        printf("Nepodarilo sa otvoriť súbor na zápis.\n");
        return;
    }

    for (int i = 0; i < moja_stanica->track_count; i++) {
        struct car* current = moja_stanica->tracks[i];
        while (current != NULL) {
            fprintf(file, "%s %d\n", current->value, current->capacity);
            current = current->next;
        }
    }

    fclose(file);
    printf("Údaje boli úspešne uložené do data.txt.\n");
}

// Funkcia pre načítanie údajov zo súboru
void load_from_file(struct station* moja_stanica) {
    FILE *file = fopen("data.txt", "r");
    if (file == NULL) {
        printf("Súbor data.txt nebol nájdený. Začíname s prázdnou stanicou.\n");
        return;
    }

    char target[TARGET_SIZE];
    int capacity;
    while (fscanf(file, "%s %d", target, &capacity) != EOF) {
        add_target_capacity(moja_stanica, target, capacity);
    }

    fclose(file);
    printf("Údaje boli úspešne načítané zo súboru data.txt.\n");
}