1 /**
2 * Copyright © DiamondMVC 2018
3 * License: MIT (https://github.com/DiamondMVC/Diamond/blob/master/LICENSE)
4 * Author: Jacob Jensen (bausshf)
5 */
6 module diamond.data.i18n.messages;
7 
8 import diamond.core.apptype;
9 
10 static if (isWeb)
11 {
12 
13   import diamond.http;
14 
15   /// Alias for an associative array.
16   private alias Language = string[string];
17 
18   /// A collection of localization messages.
19   private __gshared Language[string] _messages;
20 
21   /// The default language.
22   private __gshared string _defaultLanguage;
23 
24   /**
25   * Sets the default language of the application.
26   * Params:
27   *   language = The language.
28   */
29   void setDefaultLanguage(string language)
30   {
31     _defaultLanguage = language;
32   }
33 
34   /**
35   * Gets a message.
36   * Params:
37   *   clent = The client to use the language of.
38   *   key =   The key of the message to retrieve.
39   * Returns:
40   *   The message if found for the client's language, otherwise it will attempt to get the default language's message and if that fails too then it returns an empty string.
41   */
42   string getMessage(HttpClient client, string key)
43   {
44     return getMessage(client.language, key);
45   }
46 
47   /**
48   * Gets a message.
49   * Params:
50   *   languageName = The language to retrieve a message from.
51   *   key =          The key of the message to retrieve.
52   * Returns:
53   *   The message if found for the specified language, otherwise it will attempt to get the default language's message and if that fails too then it returns an empty string.
54   */
55   string getMessage(string languageName, string key)
56   {
57     auto language = _messages.get(languageName, null);
58 
59     if (!language)
60     {
61       language = _messages.get(_defaultLanguage, null);
62     }
63 
64     if (!language)
65     {
66       return "";
67     }
68 
69     return language.get(key, "");
70   }
71 
72   /**
73   * Adds a message to a specific language.
74   * Params:
75   *   language = The language to add the message to.
76   *   key =      The key of the message.
77   *   message =  The message to add.
78   */
79   void addMessage(string language, string key, string message)
80   {
81     _messages[language][key] = message;
82   }
83 }