using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using IniParser;
using IniParser.Model;

namespace Elwig.Helpers {
    public class Config {

        private readonly string FileName;
        public string DatabaseFile = App.DataPath + "database.sqlite3";
        public string? DatabaseLog = null;
        public IEnumerable<string[]> Scales;
        private readonly LinkedList<string[]> ScaleList = new();

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

        public void Read() {
            var parser = new FileIniDataParser();
            IniData? ini = null;
            try {
                ini = parser.ReadFile(FileName, Encoding.UTF8);
            } catch {}

            if (ini == null || !ini.TryGetKey("database.file", out string db)) {
                DatabaseFile = App.DataPath + "database.sqlite3";
            } else if (db.Length > 1 && (db[1] == ':' || db[0] == '/' || db[0] == '\\')) {
                DatabaseFile = db;
            } else {
                DatabaseFile = App.DataPath + db;
            }

            if (ini == null || !ini.TryGetKey("database.log", out string log)) {
                DatabaseLog = null;
            } else if (log.Length > 1 && (log[1] == ':' || log[0] == '/' || log[0] == '\\')) {
                DatabaseLog = log;
            } else {
                DatabaseLog = App.DataPath + log;
            }

            ScaleList.Clear();
            Scales = ScaleList;
            if (ini != null) {
                foreach (var s in ini.Sections.Where(s => s.SectionName.StartsWith("scale."))) {
                    ScaleList.AddLast(new string[] {
                        s.SectionName[6..], s.Keys["type"], s.Keys["model"], s.Keys["connection"],
                        s.Keys["empty"], s.Keys["filling"], s.Keys["limit"]
                    });
                }
            }
        }

        public void Write() {
            using var file = new StreamWriter(FileName, false, Encoding.UTF8);
            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");
            }
        }
    }
}