using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Windows;

namespace TwoMbit
{
    public class Language
    {
        XmlDocument doc;
        string langpath;
        bool standardLang;

        public Language(string xmlfile)
        {
            setLang(xmlfile);
            load();
        }

        public void setLang(string xmlfile)
        {
            langpath = App.APP_DIR + App.LANGUAGE_DIR + xmlfile;
            standardLang = xmlfile == App.LANGUAGE_FILE;
            doc = null;
        }

        public string get(string key)
        {
            if (doc == null) {
                load();
            }

            XmlElement root = doc.DocumentElement;
            foreach(XmlNode content in root.ChildNodes) {
                if(content["id"].InnerText == key) {
                    return content["body"].InnerText;
                }
            }
            throw new Exception("language key: " + key + " is not found");
        }

        private void load()
        {
            try {
                doc = new XmlDocument();
                doc.Load(langpath);
            } catch {
                if (standardLang) {
                    throw new Exception("Couldn't load language file, make sure your language files are in the folder: " + App.LANGUAGE_DIR + ", relative to your application");
                } else {
                    MessageBox.Show("Couldn't load language file, try switching to standard language", "Warning");
                    setLang(App.LANGUAGE_FILE);
                    load();
                }
            }
        }
    }
}
