using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;


namespace isn
{
   
    partial class Program
    {
     
        private static void StoreApiKey(IEnumerable<string> storeArgs)
        {
            var args = storeoptions.Parse(storeArgs);
            if (shouldShowPushHelp)
            {
                // output the options
                Console.Error.WriteLine("Push Options:");
                storeoptions.WriteOptionDescriptions(Console.Out);
            }
            else
            {
                apiKey = args[0];
                EnsureKeyStored();
            }
        }

         public static void EnsureKeyStored()
        {
            if (source == null)
            {
                if (Settings.DefaultSource == null)
                    return;
                source = Settings.DefaultSource;
            }

            if (Settings.Sources.ContainsKey(source))
            {
                if (apiKey == null)
                {
                    // Une suppression
                    Settings.Sources.Remove(source);
                    if (Settings.DefaultSource == source) Settings.DefaultSource = null;
                }
                else
                {
                    // Une mise À jour
                    string ptd = Protector.Protect(apiKey);
                    Settings.Sources[source].ApiKey = ptd;
                    if (Settings.DefaultSource == null) Settings.DefaultSource = source;
                }
            }
            else if (apiKey != null)
            {
                // une addition
                string ptd = Protector.Protect(apiKey);
                Settings.Sources.Add(source, new SourceSettings { ApiKey = ptd });
            }
            SaveConfig();
        }
        public static void SaveConfig()
        {
            FileInfo cfgSettingIf = new FileInfo(_configFileName);
            if (!cfgSettingIf.Directory.Exists) cfgSettingIf.Directory.Create();
            File.WriteAllText(
                cfgSettingIf.FullName, 
                JsonConvert.SerializeObject(
                    Settings,
                    Formatting.Indented
            ));

        }
    }
}