#include "game.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define EMPTY_CHAR '.' // Leeres Kästchen

typedef enum { HORIZONTAL, VERTICAL } Direction;

// 1. Funktion – Array initialisieren
static void initializeArray(char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN], unsigned int size)
{
    for (unsigned int y = 0; y < size; y++)
        for (unsigned int x = 0; x < size; x++)
            salad[y][x] = EMPTY_CHAR;
}

// 2. Funktion – prüfen, ob Wort passt
static int canPlace(const char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN],
                    unsigned int size, unsigned int x, unsigned int y,
                    const char *word, Direction dir)
{
    unsigned int len = strlen(word);
    if ((dir == HORIZONTAL && x + len > size) || (dir == VERTICAL && y + len > size))
        return 0;

    for (unsigned int i = 0; i < len; i++) {
        if ((dir == HORIZONTAL && salad[y][x + i] != EMPTY_CHAR) ||
            (dir == VERTICAL && salad[y + i][x] != EMPTY_CHAR))
            return 0;
    }
    return 1;
}

// 3. Funktion – Wort eintragen
static void placeWord(char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN],
                      unsigned int x, unsigned int y, const char *word, Direction dir)
{
    for (unsigned int i = 0; i < strlen(word); i++) {
        if (dir == HORIZONTAL)
            salad[y][x + i] = word[i];
        else
            salad[y + i][x] = word[i];
    }
}

// 4. Funktion – leere Felder mit Zufallsbuchstaben füllen
static void fillRandomLetters(char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN], unsigned int size)
{
    for (unsigned int y = 0; y < size; y++)
        for (unsigned int x = 0; x < size; x++)
            if (salad[y][x] == EMPTY_CHAR)
                salad[y][x] = 'A' + (rand() % 26);
}

// Hauptfunktion – Wortsalat erzeugen
int createWordSalad(char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN],
                    unsigned int size, const char words[][MAX_WORD_LEN],
                    unsigned int wordCount)
{
    srand(time(NULL));
    initializeArray(salad, size);

    int placed = 0;
    for (unsigned int i = 0; i < wordCount; i++) {
        int success = 0;
        for (int tries = 0; tries < 1000 && !success; tries++) {
            unsigned int x = rand() % size;
            unsigned int y = rand() % size;
            Direction dir = rand() % 2 ? HORIZONTAL : VERTICAL;

            if (canPlace(salad, size, x, y, words[i], dir)) {
                placeWord(salad, x, y, words[i], dir);
                success = 1;
                placed++;
            }
        }
    }

    fillRandomLetters(salad, size);
    return placed;
}

// Ausgabe-Funktion
void showWordSalad(const char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN], unsigned int size)
{
    for (unsigned int y = 0; y < size; y++) {
        for (unsigned int x = 0; x < size; x++)
            printf("%c ", salad[y][x]);
        printf("\n");
    }
}