// See https://aka.ms/new-console-template for more information
using Domain;
using Infrastructure;
using System.ComponentModel;
using System.Text.Json;
using System.Text.Json.Serialization;

Console.WriteLine("Hello, World!");
Player perso = new Player();
var fileName = $"C:/newCharacter.json";
const string roll = "roll";
const string createperso = "createperso";

while (true)
{
    string? methodToExec = Console.ReadLine();
    if (methodToExec != null)
    {

        switch (methodToExec.ToLower())
        {
            case roll:
                Console.WriteLine(DiceService.RollDices(1, 100));
                break;

            case createperso:
                string jsonPerso = "";
                object createPerso = await CreatePerso(perso, fileName, jsonPerso);
                Console.Write(createPerso);
                break;
        }
    }
}

static int RollInitialStat()
{
    var rollValue = DiceService.RollDices(1, 10);
    rollValue += DiceService.RollDices(1, 10);
    rollValue += 30;
    return rollValue;
}

static async Task<string> CreatePerso(Player perso, string fileName, string jsonPerso)
{
    perso = InitRandomStat();
    jsonPerso = JsonSerializer.Serialize<Player>(perso);
    //if (File.Exists(fileName))
    //{
    //    if (IsFileLocked(fileName))
    //    {
    //        Thread.Sleep(1000);
    //    }
    //    File.Delete(fileName);
    //}
    //if (IsFileLocked(fileName))
    //{
    //    Thread.Sleep(1000);
    //}
    //if (!File.Exists(fileName))
    //    File.Create(fileName);
    //await File.WriteAllTextAsync(fileName, jsonPerso);
    return jsonPerso;
}

static Player InitRandomStat()
{
    return new Player
    {
        AG = RollInitialStat(),
        CC = RollInitialStat(),
        CT = RollInitialStat(),
        E = RollInitialStat(),
        F = RollInitialStat(),
        FM = RollInitialStat(),
        INT = RollInitialStat(),
        PER = RollInitialStat(),
        SOC = RollInitialStat()
    };
}

static bool IsFileLocked(string filePath)
{
    try
    {
        using (File.Open(filePath, FileMode.Open))
        {
            return true;
        }
    }
    catch (IOException e)
    {
        Console.WriteLine("Exception occured while deleting the file, Exception is {e}", e);
    }

    return false;
}