// Copyright © Selmo Technology GmbH. All Rights Reserved

using Newtonsoft.Json;
using SelmoStudio.Hmi.Common.SelmoProject.ProcessValueDefinition;
using SelmoStudio.Hmi.Server.Diagnostic;
using SelmoStudio.Hmi.Server.SelmoHmi.Shared.Model;

namespace SelmoStudio.Hmi.Server.Diagnostic
{
    public static class DiagnosticSettingHelper
    {
        public const string ProjectDataFileName = "diagnosticSettings.json";
        public const string DiagnosticFolderName = "DiagnosticSettings";

        public static DiagnosticSettings GetDiagnosticSettings()
        {
            var path = GetRelativePath(ProjectDataFileName);
            string dataAsString = File.ReadAllText(path);
            var processValueDefinitions = JsonConvert.DeserializeObject<DiagnosticSettings>(dataAsString)!;
            return processValueDefinitions;
        }

        public static bool CreateIfNotExists()
        {
            var path = GetRelativePath(ProjectDataFileName);

            DiagnosticSettings empty = new()
            {
                LogValueChangeFromDevice = false,
                LogValueWriteToDevice = false
            };

            if (File.Exists(path))
            {
                return false;
            }

            var folderPath = GetFolderPath();
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            var text = JsonConvert.SerializeObject(empty);
            File.WriteAllText(path, text);
            return true;
        }

        private static string GetRelativePath(string fileName)
        {
            var folderPath = GetFolderPath();
            var fullFilePath = Path.Combine(folderPath, fileName);
            return fullFilePath;
        }

        private static string GetFolderPath()
        {
            var appBasePath = AppDomain.CurrentDomain.BaseDirectory;

            var folderPath = Path.Combine(appBasePath, DiagnosticFolderName);
            return folderPath;
        }
    }
}