using System.Net;
using System.Text;
using MySql.Data.MySqlClient;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;

namespace Server
{
    public class CreateLog
    {
        private static string secretKey = "stronk-key-much-sercret-much-more-stronk-stronk-key-much-sercret-much-more-stronk";
        public static bool ValidateToken(string token)
        {
            try
            {
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
                var tokenHandler = new JwtSecurityTokenHandler();
                var validationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidIssuer = "TimeLogServer",
                    ValidAudience = "TimeLogWebsite",
                    IssuerSigningKey = key
                };

                var principal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);
                return validatedToken != null;
            }
            catch
            {
                return false;
            }
        }
        public static void run(MySqlConnection conn, HttpListenerRequest request, HttpListenerResponse response)
        {
            try
            {
                var headers = request.Headers;
                string? token = headers["token"];
                if (!ValidateToken(token))
                {
                    throw new Exception("Invalid token");
                }
                // open connection
                conn.Open();
                // prepare SQL query
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = @"INSERT INTO Timelog(user,project,date,time) VALUES(@user,@project,@date,@time);";

                var queryString = request.QueryString;
                string? user = queryString["user"];
                string? project = queryString["project"];
                string? time = queryString["time"];
                string? date = queryString["date"];
                // TODO validate somehow that the user who send the date is the
                // same user who has token, validate the project belongs to the
                // user
                int myInt;
                bool isValid = int.TryParse(time, out myInt);
                if (!string.IsNullOrEmpty(time) && isValid && myInt > 0) { }

                if (!string.IsNullOrEmpty(date)) // use regex to validate{ }

                    if (string.IsNullOrEmpty(user)) // select * from User Where user=@user; 
                    { }
                if (!string.IsNullOrEmpty(project))// select * from Project Where project=@project;
                { }

                cmd.Parameters.AddWithValue("@user", user);
                cmd.Parameters.AddWithValue("@project", project);
                cmd.Parameters.AddWithValue("@time", time);
                cmd.Parameters.AddWithValue("@date", date);
                // execute query and read results
                cmd.ExecuteNonQuery();

                response.StatusCode = (int)HttpStatusCode.OK;
                response.StatusDescription = "Status OK";

            }
            catch (Exception ex)
            {
                string errorMessage = $"Error: {ex.Message}";
                byte[] buffer = Encoding.UTF8.GetBytes(errorMessage);
                response.ContentType = "text/plain";
                response.ContentLength64 = buffer.Length;
                response.OutputStream.Write(buffer, 0, buffer.Length);
            }
            finally
            {
                // close db connection
                conn.Close();
            }
        }
    }
}

