using AudioWallpaper.ActivityWatch;
using AudioWallpaper.SSO;
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace AudioWallpaper.Tools {
    public class SentenceHelper : IDisposable {
        public event EventHandler<FocusStatusRecord>? SentenceChanged;

        private int interval = 1000 * 3; // 默认3秒
        private Task? task = null;
        private CancellationTokenSource? cts = null;
        private CancellationTokenSource stateChangeCts = new();
        private readonly object stateLock = new();

        private LoginMeta? loginMeta = null;
        private bool isUse = false;

        public void Start() {
            if (task != null && !task.IsCompleted)
                return; // 已在运行中

            cts = new CancellationTokenSource();
            task = RunAsync(cts.Token);
        }

        public void Stop() {
            cts?.Cancel();
            task = null;
        }
        /// <summary>
        /// 更新登录状态
        /// </summary>
        /// <param name="loginMeta">登录状态对象</param>
        public void UpdateLoginState(LoginMeta loginMeta) {
            Console.WriteLine("11111111111111");
            lock (stateLock) {
                this.loginMeta = loginMeta;
            }
            NotifyStateChange();
        }
        /// <summary>
        /// 更新启用状态
        /// </summary>
        /// <param name="isUse">是否启用</param>
        public void UpdateUseState(bool isUse) {
            lock (stateLock) {
                this.isUse = isUse;
            }
            NotifyStateChange();
        }
        /// <summary>
        /// 设置任务执行间隔
        /// </summary>
        /// <param name="newInterval">任务执行间隔，单位毫秒</param>
        public void SetInterval(int newInterval) {
            this.interval = newInterval;
            NotifyStateChange();
        }

        public int GetInterval() => this.interval;

        private void NotifyStateChange() {
            // 取消当前等待操作，强制立即重新检查状态
            lock (stateLock) {
                stateChangeCts.Cancel();
                stateChangeCts.Dispose();
                stateChangeCts = new CancellationTokenSource();
            }
        }

        public void Dispose() {
            Stop();
            stateChangeCts?.Dispose();
            cts?.Dispose();
        }

        private async Task RunAsync(CancellationToken c_token) {
            Console.WriteLine("SentenceHelper 任务启动");

            while (!c_token.IsCancellationRequested) {
                // 创建组合令牌：任务取消 + 状态变化
                using var combinedCts = CancellationTokenSource.CreateLinkedTokenSource(
                    c_token,
                    stateChangeCts.Token
                );

                try {
                    // 原子性状态检查
                    bool shouldRun;
                    lock (stateLock) {
                        shouldRun = isUse &&
                                   loginMeta != null &&
                                   loginMeta.IsLoggedIn;
                    }

                    if (!shouldRun) {
                        Console.WriteLine("SentenceHelper: 未启用或未登录，等待状态变化");

                        // 无限等待直到状态变化或任务取消
                        await Task.Delay(Timeout.Infinite, combinedCts.Token);
                        continue;
                    }

                    // 主要业务逻辑
                    await ExecuteBusinessLogic(combinedCts.Token);

                    // 业务操作完成后等待间隔（可被取消）
                    await Task.Delay(interval, combinedCts.Token);
                } catch (OperationCanceledException) {
                    // 状态变化或任务取消：立即响应
                    Console.WriteLine("SentenceHelper: 操作被取消，响应状态变化");
                } catch (Exception ex) {
                    Console.WriteLine($"SentenceHelper: 任务异常: {ex.Message}");
                }
            }

            Console.WriteLine("SentenceHelper: 任务已停止");
        }

        private async Task ExecuteBusinessLogic(CancellationToken token) {
            Console.WriteLine("SentenceHelper: 执行业务逻辑");
            try {
                // 1. 获取活动数据
                ActivityWatchClient client = new ActivityWatchClient("aw-watcher-window_回忆如此多娇");
                var ranges = ActivityWatchClient.GenerateTimeRanges();
                var time = ranges["last_30_minutes"];
                var list = await client.GetEventsAsync(time["start"], time["end"]);

                // 2. 分析活动数据
                ActivityAnalyzer analyzer = new ActivityAnalyzer();
                var results = analyzer.AnalyzeFromRawData(list);
                string jsonContent = JsonSerializer.Serialize(results);

                // 3. 调试输出
                Program.WindowManager.ShowBubble("SentenceHelper: 测试代码");

                /* 
                HttpHelper httpHelper = new HttpHelper();
                string url = "http://accompany.com/api/getmessage.php";
                string? token = Program.SSOM.GetAccessToken();
                
                if (string.IsNullOrWhiteSpace(token)) 
                {
                    Console.WriteLine("SentenceHelper: 获取Token失败，无法获取句子");
                    return;
                }
                
                var formResponse = await httpHelper.PostAsync(
                    url,
                    new Dictionary<string, string>
                    {
                        {"token", token},
                        {"data", jsonContent}
                    },
                    "application/x-www-form-urlencoded",
                    token);

                var parser = new FocusStatusParser();
                var latestRecord = parser.GetLatestRecord(formResponse);
                
                // 触发事件
                SentenceChanged?.Invoke(this, latestRecord);
                */
            } catch (OperationCanceledException) {
                Console.WriteLine("SentenceHelper: 业务逻辑被取消");
                throw; // 重新抛出以被外层捕获
            } catch (Exception ex) {
                Console.WriteLine($"SentenceHelper: 业务逻辑异常: {ex.Message}");
            }
        }
    }
}