using System.IO;
using static SimpleJson.SimpleJson;

namespace Katteker.Types
{
    /// <summary>
    /// Configuration of a Katteker-Deployment
    /// </summary>
    internal class KattekerConfig
    {
        /// <summary>
        /// Publish path
        /// </summary>
        public string Publish { get; set; } = null!;

        /// <summary>
        /// Name of the changelog file.
        /// </summary>
        public string? Changelog { get; set; }

        /// <summary>
        /// Channel of the application. (Alpha, Beta and so on...)
        /// </summary>
        public string? Channel { get; set; }

        /// <summary>
        /// Read file and deserialize content.
        /// </summary>
        /// <param name="path">path of the file.</param>
        /// <param name="config"></param>
        /// <returns>this object</returns>
        /// <exception cref="FileNotFoundException"></exception>
        public static bool TryReadFromFile(string path, out KattekerConfig? config)
        {
            if (!File.Exists(path)) throw new FileNotFoundException();
            var content = File.ReadAllText(path);
            try
            {
                config = DeserializeObject<KattekerConfig>(content);
                return true;
            }
            catch
            {
                config = default;
                return false;
            }
        }

        /// <summary>
        /// Serialize object and write to file.
        /// </summary>
        /// <param name="path">path of the file.</param>
        public void WriteToFile(string path)
        {
            if (File.Exists(path)) File.Delete(path);
            var json = SerializeObject(this);
            File.WriteAllText(path, json);
        }
    }
}