using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Configuration;

namespace Elwig.Helpers {
    public class Config {

        private readonly string FileName;
        public bool Debug;
        public string DatabaseFile = App.DataPath + "database.sqlite3";
        public string? DatabaseLog = null;
        public string? Branch = null;
        public IList<string?[]> Scales;
        private readonly List<string?[]> ScaleList = [];
        private static readonly string[] trueValues = ["1", "true", "yes", "on"];

        public Config(string filename) {
            FileName = filename;
            Scales = ScaleList;
            Read();
        }

        public void Read() {
            var config = new ConfigurationBuilder().AddIniFile(FileName).Build();

            DatabaseFile = Path.Combine(App.DataPath, config["database:file"] ?? "database.sqlite3");
            var log = config["database:log"];
            DatabaseLog = log != null ? Path.Combine(App.DataPath, log) : null;
            Branch = config["general:branch"];
            Debug = trueValues.Contains(config["general:debug"]?.ToLower());

            var scales = config.AsEnumerable().Where(i => i.Key.StartsWith("scale.")).GroupBy(i => i.Key.Split(':')[0][6..]).Select(i => i.Key);
            ScaleList.Clear();
            Scales = ScaleList;
            foreach (var s in scales) {
                string? scaleLog = config[$"scale.{s}:log"];
                if (scaleLog != null) scaleLog = Path.Combine(App.DataPath, scaleLog);
                ScaleList.Add([
                    s, config[$"scale.{s}:type"], config[$"scale.{s}:model"], config[$"scale.{s}:connection"],
                    config[$"scale.{s}:empty"], config[$"scale.{s}:filling"], config[$"scale.{s}:limit"], scaleLog
                ]);
            }
        }

        public void Write() {
            using var file = new StreamWriter(FileName, false, Utils.UTF8);
            file.Write($"\r\n[general]\r\n");
            if (Branch != null) file.Write($"branch = {Branch}\r\n");
            if (Debug) file.Write("debug = true\r\n");
            file.Write($"\r\n[database]\r\nfile = {DatabaseFile}\r\n");
            if (DatabaseLog != null) file.Write($"log = {DatabaseLog}\r\n");
            foreach (var s in ScaleList) {
                file.Write($"\r\n[scale.{s[0]}]\r\ntype = {s[1]}\r\nmodel = {s[2]}\r\nconnection = {s[3]}\r\n");
                if (s[4] != null) file.Write($"empty = {s[4]}\r\n");
                if (s[5] != null) file.Write($"filling = {s[5]}\r\n");
                if (s[6] != null) file.Write($"limit = {s[6]}\r\n");
                if (s[7] != null) file.Write($"log = {s[7]}\r\n");
            }
        }
    }
}