using System;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using System.ComponentModel;

namespace EliteBGS.Util {
    public class Config {
        private string config_folder = null;
        private string config_file = null;

        private AppConfig global_config = new AppConfig();

        public Config() {
            DetermineConfigFolder();
        }

        public string ConfigPath => config_folder;

        public AppConfig Global => global_config;

        private void DetermineConfigFolder() {
            string folder = Environment.ExpandEnvironmentVariables("%appdata%\\EliteBGS");

            if (!Directory.Exists(folder)) {
                Directory.CreateDirectory(folder);
            }

            config_folder = folder;
            config_file = Path.Combine(config_folder, "config.json");
        }

        public void SaveGlobal() {
            var serializer = JsonSerializer.CreateDefault();
            using (FileStream filestream = File.OpenWrite(config_file)) {
                filestream.SetLength(0);
                filestream.Flush();
                using (StreamWriter file = new StreamWriter(filestream, Encoding.UTF8)) {
                    var stream = new JsonTextWriter(file);
                    stream.Formatting = Formatting.Indented;
                    serializer.Serialize(stream, global_config);
                }
            }
        }

        public void LoadGlobal() {
            var serializer = JsonSerializer.CreateDefault();
            using (var file = new StreamReader(File.OpenRead(config_file), Encoding.UTF8)) {
                var stream = new JsonTextReader(file);
                var app = serializer.Deserialize<AppConfig>(stream);

                if (app != null) {
                    this.global_config = app;
                }
            }
        }
    }
}
