using NLog;
using Server.Git;
using System.Threading;
using System.Threading.Tasks;

namespace Server.System
{
    public class GItWebhook
    {
        private static readonly NLog.ILogger logger = LogManager.GetCurrentClassLogger();

        public static Thread thread;

        private static AbstractGit git;

        public static string Process(HttpContext context)
        {
            //TODO 아무때나 호출되지 않게 만들기
            string Response;
            try
            {
                string eaDelivery = context.Request.Headers["X-Gitea-Delivery"];
                string eaEvent = context.Request.Headers["X-Gitea-Event"];
                string eaEventType = context.Request.Headers["X-Gitea-Event-Type"];
                string eaSignature = context.Request.Headers["X-Gitea-Signature"];

                Console.WriteLine($"X-Gitea-Delivery : {eaDelivery}");
                Console.WriteLine($"X-Gitea-Event : {eaEvent}");
                Console.WriteLine($"X-Gitea-Event-Type : {eaEventType}");
                Console.WriteLine($"X-Gitea-Signature : {eaSignature}");

                Console.WriteLine(thread.ThreadState);

                //Unstarted
                if (thread.ThreadState == ThreadState.Unstarted)
                {
                    thread.Start();
                }
                else if (thread.ThreadState == ThreadState.Stopped)
                {
                    thread = new Thread(git.Init);
                    thread.Start();
                } 
                else if (thread.ThreadState == ThreadState.WaitSleepJoin || thread.ThreadState == ThreadState.Running)
                {
                    git.isRestart = true;
                }
       

                ErrorResp error = new ErrorResp();
                error.status = 200;
                error.message = "Success";
                Response = error.ToJson();
            }
            catch (RuntimeException ex)
            {
                ErrorResp error = new ErrorResp(ex);
                Response = error.ToJson();
                logger.Error("GetErrorResponse : " + Response);
            }
            catch (Exception ex)
            {
                ErrorResp error = new ErrorResp();
                Response = error.ToJson();
                logger.Error("GetErrorResponse : " + ex.ToString());
            }
            return Response;

        }

        public static void Init()
        {
            git = new XlsxToJson();
            thread = new Thread(git.Init);
        }
    }
}