#if UNITY_EDITOR
using System;
using UnityEditor;
using System.Net;
using System.Net.Sockets;

namespace hive
{
    public class RTTContext 
    {
        private bool isReadyForUseHiveRTT = false;
        private static readonly Lazy<RTTContext> instance = new Lazy<RTTContext>(() => new RTTContext());
        
        public int ServicePort
        {
            get
            {
                InitalizePort();
                UnityEngine.Debug.Log(EditorPrefs.GetInt(RTT_EDITOR_KEY_SERVICE_PORT));
                return EditorPrefs.GetInt(RTT_EDITOR_KEY_SERVICE_PORT);
            }
            set => EditorPrefs.SetInt(RTT_EDITOR_KEY_SERVICE_PORT, value);
        }

        public bool IsUseHiveRTT
        {
            get => EditorPrefs.GetBool(RTT_EDITOR_KEY_IS_USE_RTT, false);
            set => EditorPrefs.SetBool(RTT_EDITOR_KEY_IS_USE_RTT, value);
        }

        public bool IsReadyForUseHiveRTT
        {
            get => isReadyForUseHiveRTT && EditorPrefs.GetBool(RTT_EDITOR_KEY_IS_USE_RTT, false);
        }

        public void SetReadyForUseHiveRTT(bool isReady)
        {
            isReadyForUseHiveRTT = isReady;
        }

        public static RTTContext Instance => instance.Value;

        private string RTT_EDITOR_KEY_SERVICE_PORT = GetUnityProjectIDBasedKey("RTTServicePort");
        private string RTT_EDITOR_KEY_IS_USE_RTT = GetUnityProjectIDBasedKey("IsUseHiveRTT");
        private RTTContext() {
            InitalizePort();
        }

        private void InitalizePort() {
            if (!EditorPrefs.HasKey(RTT_EDITOR_KEY_SERVICE_PORT)) {
                ServicePort = GetAvailablePort();
            }
        }

        private int GetAvailablePort() {
            TcpListener listener = new TcpListener(IPAddress.Loopback, 0);
            listener.Start();
            int port = ((IPEndPoint)listener.LocalEndpoint).Port;
            listener.Stop();
            return port;
        }

        /**
        client id에 기반한 키
        */
        private static string GetUnityProjectIDBasedKey(string key) {
            return HiveUnityProjectID.GetProjectIDWithPlatform() + key;
        }

    }
}
#endif