using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.NetworkInformation;
using System.Data;
using System.Data.SqlClient;
using FCOMMON;
using Project.Web.Model;

namespace Project.Web
{
    // Important: Allows JavaScript to see this class
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [ComVisible(true)]
    public partial class MachineBridge
    {
        // Reference to the main form to update logic
        private Dialog.fDashboard _host;

        // WebSocket 서버 인스턴스
        private static Project.Web.WebSocketServer _wsServer;
        private static readonly object _wsLock = new object();

        private const int WS_PORT = 8082;

        public MachineBridge(Dialog.fDashboard host)
        {
            _host = host;
            StartWebSocketServer();
        }

        #region WebSocket Server Control

        /// <summary>
        /// WebSocket 서버 시작
        /// </summary>
        private void StartWebSocketServer()
        {
            lock (_wsLock)
            {
                if (_wsServer != null)
                {
                    Console.WriteLine("[WS] WebSocket server already running");
                    return;
                }

                try
                {
                    string url = $"http://localhost:{WS_PORT}/";
                    _wsServer = new Project.Web.WebSocketServer(url, this);
                    _wsServer.Start();
                    Console.WriteLine($"[WS] WebSocket server started on port {WS_PORT}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[WS] Failed to start WebSocket server: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// WebSocket 서버 중지
        /// </summary>
        public static void StopWebSocketServer()
        {
            lock (_wsLock)
            {
                if (_wsServer != null)
                {
                    _wsServer.Stop();
                    _wsServer = null;
                    Console.WriteLine("[WS] WebSocket server stopped");
                }
            }
        }

        /// <summary>
        /// WebSocket 서버 실행 여부 확인
        /// </summary>
        public static bool IsWebSocketServerRunning()
        {
            lock (_wsLock)
            {
                return _wsServer != null;
            }
        }

        #endregion

        #region App Info

        /// <summary>
        /// 애플리케이션 버전 정보 반환
        /// </summary>
        public string GetAppVersion()
        {
            try
            {
                var productVersion = Application.ProductVersion;
                var maxVersion = DBM.GetMaxVersion();
                var hasNewVersion = false;
                
                if (!string.IsNullOrEmpty(maxVersion))
                {
                    var verchk = productVersion.CompareTo(maxVersion);
                    if (verchk < 0)
                    {
                        hasNewVersion = true;
                    }
                }

                return JsonConvert.SerializeObject(new
                {
                    Success = true,
                    ProductName = Application.ProductName,
                    ProductVersion = productVersion,
                    DisplayVersion = $"{Application.ProductName} v{productVersion}",
                    MaxVersion = maxVersion,
                    HasNewVersion = hasNewVersion
                });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = ex.Message });
            }
        }

        #endregion
    }

    /// <summary>
    /// 로그인 결과 클래스
    /// </summary>
    public class LoginResult
    {
        public bool Success { get; set; }
        public string Message { get; set; }
        public string RedirectUrl { get; set; }
        public string UserName { get; set; }
        public string VersionWarning { get; set; }
    }
}
