using System;
using System.Diagnostics;
using System.IO;
using Newtonsoft.Json;

namespace ZB.MOM.WW.GRAccess.Cli.Session
{
    public class SessionInfo
    {
        [JsonProperty("galaxyName")]
        public string GalaxyName { get; set; }

        [JsonProperty("nodeName")]
        public string NodeName { get; set; }

        [JsonProperty("pipeName")]
        public string PipeName { get; set; }

        [JsonProperty("processId")]
        public int ProcessId { get; set; }

        [JsonProperty("startedAtUtc")]
        public DateTime StartedAtUtc { get; set; }

        private static string SessionsDir =>
            Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                "ZB.MOM.WW.GRAccess.Cli",
                "sessions");

        public static string GetSessionFilePath(string galaxyName)
        {
            return Path.Combine(SessionsDir, galaxyName.ToLowerInvariant() + ".json");
        }

        public static SessionInfo Load(string galaxyName)
        {
            var path = GetSessionFilePath(galaxyName);
            if (!File.Exists(path))
                return null;

            try
            {
                var json = File.ReadAllText(path);
                return JsonConvert.DeserializeObject<SessionInfo>(json);
            }
            catch
            {
                return null;
            }
        }

        public void Save()
        {
            var path = GetSessionFilePath(GalaxyName);
            Directory.CreateDirectory(Path.GetDirectoryName(path));
            var json = JsonConvert.SerializeObject(this, Formatting.Indented);
            File.WriteAllText(path, json);
        }

        public void Delete()
        {
            var path = GetSessionFilePath(GalaxyName);
            if (File.Exists(path))
                File.Delete(path);
        }

        /// <summary>
        /// Check if the daemon process is still running.
        /// </summary>
        public bool IsAlive()
        {
            try
            {
                var process = Process.GetProcessById(ProcessId);
                return !process.HasExited;
            }
            catch
            {
                return false;
            }
        }
    }
}
