1 /++
2  + Authors: Stephan Dilly, lastname dot firstname at gmail dot com
3  + Copyright: MIT
4  +/
5 module ask.locale;
6 
7 ///
8 interface ITextManager
9 {
10 	/++
11 	 + returns the localized text string depending on the loaded locale database
12 	 +
13 	 + params:
14 	 +	_key = loca lookup key
15 	 +
16 	 + see_also:
17 	 +	`this`, `AlexaText`, `LocaParser`
18 	 +/
19 	string getText(int _key) const pure nothrow;
20 }
21 
22 ///
23 struct AlexaText
24 {
25 	///
26 	int key;
27 	///
28 	string text;
29 }
30 
31 /// template to parse csv of loca entries
32 string LocaParser(E, string input)()
33 {
34 	import std.string : splitLines, strip;
35 	import std.algorithm : startsWith;
36 	import std.format : format;
37 	import std.array : split;
38 
39 	enum string[] lines = input.splitLines;
40 
41 	string res = "[";
42 
43 	allMembers: foreach (enumMember; __traits(allMembers, E))
44 	{
45 		bool found = false;
46 
47 		foreach (line; lines)
48 		{
49 			line = line.strip;
50 
51 			if (line.startsWith(enumMember))
52 			{
53 				auto lineArgs = line.split(",");
54 
55 				auto untilFirstComma = lineArgs[0];
56 				auto locaKey = untilFirstComma.strip;
57 
58 				if (locaKey == enumMember)
59 				{
60 					auto locaText = line[untilFirstComma.length + 1 .. $].strip;
61 					auto entry = format("AlexaText(%s.%s, \"%s\"),",
62 							E.stringof, enumMember, locaText);
63 					res ~= entry ~ "\n";
64 					found = true;
65 					continue allMembers;
66 				}
67 			}
68 		}
69 
70 		assert(found, "" ~ format("loca key '%s' not found", enumMember));
71 	}
72 
73 	return res ~ "]";
74 }
75 
76 ///
77 unittest
78 {
79 	enum TextIds
80 	{
81 		key1,
82 		key2,
83 	}
84 
85 	enum testCsv = "key2, foo\n key1 ,  bar, 2  ";
86 
87 	enum AlexaText[] AlexaText_test = mixin(LocaParser!(TextIds, testCsv));
88 
89 	static assert(AlexaText_test[0].text == "bar, 2");
90 	static assert(AlexaText_test[1].text == "foo");
91 
92 	static assert(AlexaText_test[0].key == TextIds.key1);
93 	static assert(AlexaText_test[1].key == TextIds.key2);
94 }
95 
96 ///
97 unittest
98 {
99 	enum TextIds
100 	{
101 		keyTitle,
102 		key,
103 	}
104 
105 	enum testCsv = "keyTitle, foo\n key, bar";
106 
107 	enum AlexaText[] AlexaText_test = mixin(LocaParser!(TextIds, testCsv));
108 
109 	static assert(AlexaText_test[1].text == "bar");
110 }