1 module evael.system.i18n;
2 
3 import std.json;
4 import std.conv;
5 
6 class I18n
7 {
8     private JSONValue m_texts;
9 
10     public this()
11     {
12 
13     }
14 
15     /**
16      * Params:
17      *      language : ISO 639-1 code.
18      */
19     public void setLocale(in string language)
20     {
21         import std.file;
22         import std.exception;
23 
24         immutable path = "medias/translations/" ~ language ~ ".json";
25 
26         enforce(path.exists(), "Unable to find translation for language " ~ language);
27 
28         this.m_texts = parseJSON(read(path).to!string);
29     }
30 
31     /**
32      * Returns a TranslationNode for a translation key
33      */
34     @property
35     public auto opDispatch(string key)()
36     {   
37         return TranslationNode(key in this.m_texts);
38     }
39 }
40 
41 struct TranslationNode
42 {
43     private wstring m_textValue = "lang_error";
44     private const(JSONValue)* m_jsonValue = null;
45 
46     public this(const(JSONValue)* value)
47     {
48         this.m_jsonValue = value;
49     }
50 
51     public this(in wstring value)
52     {
53         this.m_textValue = value;
54     }
55 
56     @property
57     public auto opDispatch(string key)()
58     {
59         if(this.m_jsonValue !is null)
60         {
61             auto jsonValue = key in *this.m_jsonValue;
62 
63             immutable type = jsonValue.type();
64 
65             if(type == JSONType..string || type == JSONType.object)
66             {
67                 return TranslationNode(jsonValue);
68             }
69         }
70 
71         return TranslationNode(this.m_textValue);
72     }
73 
74     @property
75     public wstring str()
76     {
77         if(this.m_jsonValue !is null)
78         {
79             immutable type = this.m_jsonValue.type();
80 
81             if(type == JSONType..string)
82             {
83                 return this.m_jsonValue.str.to!wstring;
84             }
85         }
86 
87         return this.m_textValue;
88     }
89 }