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 (CurrentSource == null)
            {
                if (Settings.DefaultSourceKey == null)
                    return;
                CurrentSource = Settings.DefaultSourceKey;
            }

            if (Settings.Sources.ContainsKey(CurrentSource))
            {
                if (apiKey == null)
                {
                    // Une suppression
                    Settings.Sources.Remove(CurrentSource);
                    if (Settings.DefaultSourceKey == CurrentSource) Settings.DefaultSourceKey = null;
                }
                else
                {
                    // Une mise À jour
                    Settings.Sources[CurrentSource].SetApiKey(apiKey);
                    if (Settings.DefaultSourceKey == null) Settings.DefaultSourceKey = CurrentSource;
                }
            }
            else if (apiKey != null)
            {
                // une addition
                var setting = new SourceSettings ();
                setting.SetApiKey(apiKey);
                Settings.Sources.Add(CurrentSource, setting);
            }
            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
            ));

        }
    }
}