using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using File = System.IO.File;

namespace Valg.EVA.Skanning.Configuration
{
    public class SharedConfigurationManager : ISharedConfigurationManager
    {
        public SharedConfiguration Configuration { get; set; }
        public string FileName { get; }
        public void Save()
        {
            File.WriteAllText(FileName,JsonConvert.SerializeObject(Configuration));
        }

        public SharedConfigurationManager()
        {
            FileName = GetConfigurationFileLocation();
            if (File.Exists(FileName))
            {
                Configuration = ReadConfiguration();
            }
            else
            {
                Configuration = new SharedConfiguration();
            }
        }


        private SharedConfiguration ReadConfiguration()
        {
           return JsonConvert.DeserializeObject<SharedConfiguration>(File.ReadAllText(FileName));
        }

        private string GetConfigurationFileLocation()
        {
            var versionInfo = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location);
            var publicDirectory = Path.Combine(new DirectoryInfo(Environment.GetFolderPath(
                Environment.SpecialFolder.CommonDocuments)).Parent.FullName, versionInfo.CompanyName);

            if (!Directory.Exists(publicDirectory))
            {
                Directory.CreateDirectory(publicDirectory);
            }
            return Path.Combine(publicDirectory, "configuration.json");
        }
    }
}

