using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Globalization;
using System.Net.Sockets;
using System.Timers;
//using static Jobini;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

var app = builder.Build();

string filePath = "Setting.txt";
string scoreDbPath = "Score.txt";

//ini클래스라 해놓고 정작 파일 확장자는 txt로 설정한게 어이없네
Jobini settingini = new(filePath);
Jobini scoreDBini = new(scoreDbPath);

//Dictionary<string, string> settingValues = [];
Dictionary<string, string> scoreDB = [];

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
//csp이슈 고쳐야함 브라우저에서 csp때문에 신호 자체를 안보냄 다행히 유니티에서 보내는것은 csp체크가 꺼져있는듯
//그래서 어떻게 고침?
//대충 프론트엔드 문제라 하고 떠넘기죠?
//app.Use(async (context, next) =>
//{
//    context.Response.Headers.Append("Content-Security-Policy", "base-uri 'self'; default-src 'self'; img-src data: https:; object-src 'none'; script-src 'self'; style-src 'self'; upgrade-insecure-requests;");
//    await next();
//});

//scoreDB = [];

//기록하기
app.MapPost("submit", (string name, int score) =>
{
    
    var dbKey = scoreDBini.IniRead(name);
    if (dbKey != null)//scoreDB.ContainsKey(name))
    {
        int value = int.Parse(dbKey);

        if (value < score)//scoreDB[name] < score)
        {
            //scoreDB[name ] = score;
            scoreDBini.IniWrite(name, score.ToString());
        }
        return Results.Ok(new { Message = "A" });
    }
    else
    {
        scoreDBini.IniWrite(name, score.ToString());
        //scoreDB[name] = score;
        return Results.Ok(new { Message = "어예" });
    }
});

List<int> weekArrow = [];

//weekly Jobs (dbReset, WeekArrowGen...)
System.Timers.Timer resetTimer = new(10000); // 10000ms = 10 seconds => 1week = ?ms mol ra si bal
resetTimer.Elapsed += (sender, e) =>
{
    //TimeOnly curTime = new(DateTime.Now.Hour, DateTime.Now.Minute);
    //TimeOnly tarTime = new(0, 0); //아마 오전 12시?
    //if (System.TimeOnly.Equals(curTime, tarTime))
    //{
    //    weekArrow.Clear();
    //}
    //weekArrow.Clear();
    // Log reset actio
    var logger = app.Services.GetRequiredService<ILogger<Program>>();
    //logger.LogInformation("doWeekJobs");

    // Clear the scoreDB
    scoreDBini.Clear();
    weekArrow.Clear();
    Random random = new();
    for (int i = 0; i < random.NextInt64(int.Parse(settingini.NotNullableiniRead("minArrowNum","10")), int.Parse(settingini.NotNullableiniRead("maxArrowNum","30"))/*10,30*/); i++)
    {
        int rngNum = (int)random.NextInt64(0, 4);
        weekArrow.Add(rngNum/*(int)random.NextInt64(0, 4)*/);
        //logger.LogInformation(rngNum.ToString());
    }

};
//Random random = new();
//for (int i = 0; i < random.NextInt64(10,30/*int.Parse(scoreDBini.NotNullableiniRead("minArrowNum")), int.Parse(scoreDBini.NotNullableiniRead("maxArrowNum"))*/); i++)
//{
//    int rngNum = (int)random.NextInt64(0, 4);
//    weekArrow.Add(rngNum/*(int)random.NextInt64(0, 4)*/);
//    //logger.LogInformation(rngNum.ToString());
//}//자기 자신이 읽고있다고 못 읽으면 난 뭐 어떻게 받아들여야함? => resetTimer가 메인 스레드가 아닌 다른 스레드에서 동작한다는 카더라가 있음
resetTimer.Start();
//기록된 점수 얻기
app.MapGet("/", () => /*scoreDB);*/scoreDB = scoreDBini.ReadDictionary());//scoreDBini.ReadDictionary);

app.MapGet("WeekArrow", () => weekArrow
);

//app.UseHttpsRedirection();
app.UseStaticFiles();

//app.UseRouting();

app.UseAuthorization();

app.UseRouting();

app.MapRazorPages();

//이미minio에서 8000~8001사용중 
app.Run("http://localhost:8004");
