package com.uca.dao;

import com.uca.core.UserCore;

import java.sql.*;
import java.util.UUID;

public class _Initializer {

    public static void Init(boolean reset) {
        Connection connection = _Connector.getInstance();

        try {
            PreparedStatement statement;

            if (reset) {
                statement = connection.prepareStatement("DROP TABLE exchanges");
                statement.executeUpdate();

                statement = connection.prepareStatement("DROP TABLE pokemons");
                statement.executeUpdate();

                statement = connection.prepareStatement("DROP TABLE users");
                statement.executeUpdate();
            }

            // Initialisation des tables
            statement = connection.prepareStatement("CREATE TABLE IF NOT EXISTS users(id INT PRIMARY KEY AUTO_INCREMENT, firstname VARCHAR(100), lastname VARCHAR(100), identifier VARCHAR(100), password VARCHAR(300), last_connection DATE, upgrades INT);");
            statement.executeUpdate();

            statement = connection.prepareStatement("CREATE TABLE IF NOT EXISTS pokemons(id INT PRIMARY KEY auto_increment, id_api INT, nickname VARCHAR(100), level INT, owner INT, FOREIGN KEY (owner) REFERENCES users(id));");
            statement.executeUpdate();

            statement = connection.prepareStatement("CREATE TABLE IF NOT EXISTS exchanges(id_exch INT PRIMARY KEY auto_increment, id_pokemon_exp INT, id_pokemon_dest INT, status VARCHAR(10), " +
                                                        "FOREIGN KEY (id_pokemon_exp) REFERENCES pokemons(id), FOREIGN KEY (id_pokemon_dest) REFERENCES pokemons(id));");
            statement.executeUpdate();

            if (new UserDAO().getUserCount() == 0){
                String password = UUID.randomUUID().toString();
                UserCore.create("Admin", "Admin", "admin", password);
                System.out.println("New user generated as database were empty. Username: admin | Password: " + password);
            }

        } catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("could not create database !");
        }
    }
}
