using BoFilTest.Domain;
using IniParser.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BoFilTest.Utils
{
    class Store
    {

        private const string SECTION = "BoFilTest";
        private const string TEST_NUMBER_KEY = "test.number";
        private const string FILENAME = "store.ini";

        private readonly IniData data;
        
        IniData Load()
        {
            try
            {
                var parser = new IniParser.Parser.IniDataParser();
                var data = parser.Parse(File.ReadAllText(FILENAME));
                return data;

            }
            catch (System.IO.FileNotFoundException)
            {
                // Create default values
                var data = new IniData();
                data[SECTION][TEST_NUMBER_KEY] = 1.ToString();
                return data;
            }
        }

        public Store()
        {
            this.data = Load();
        }

        public int GetTestNumberCounter()
        {
            var s = this.data[SECTION][TEST_NUMBER_KEY];
            int result = 0;
            if (!Int32.TryParse(s, out result))
                throw new InvalidOperationException(Translated.FromKey("CANNOT_READ_TEST_NUMBER", s));
            return result;
        }

        public void IncrementTestNumberCounter()
        {
            var previous = GetTestNumberCounter();
            var next = previous+1;
            this.data[SECTION][TEST_NUMBER_KEY] = next.ToString();

            var parser = new IniParser.FileIniDataParser();
            parser.WriteFile(FILENAME, this.data);
        }

        public DefaultsConfiguration LastDefaults()
        {
            if (!this.data.Sections.ContainsSection(Configuration.DEFAULTS_SECTION_NAME))
            {
                return null;
            }
            return new DefaultsConfiguration(this.data.Sections[Configuration.DEFAULTS_SECTION_NAME]);
        }

        public void EndTest(Form lastInputs)
        {
            if (!this.data.Sections.ContainsSection(Configuration.DEFAULTS_SECTION_NAME))
            {
                this.data.Sections.AddSection(Configuration.DEFAULTS_SECTION_NAME);
            }
            var defaults = this.data.Sections[Configuration.DEFAULTS_SECTION_NAME];
            lastInputs.ApplyMapping(new FormWriter(defaults));
            IncrementTestNumberCounter();
        }
    }
}
