public void SetFontAndMaterial(LocalizedLanguage language, int outlineIndex, ref RTLTextMeshPro RTLTextMeshPro)
        {
            FontAssetDetails fontAssetDetails = LocalizationManager.Instance.GetFontAssetDetailsByLanguage(language);

            RTLTextMeshPro.font = fontAssetDetails.FontAsset;
            RTLTextMeshPro.fontSharedMaterial = fontAssetDetails.MaterialPresets[outlineIndex];
        }
    public void SetLanguage(string languageID)
    {
        m_currentLanguageID = null;

        if (ReadLanguageFile(languageID) || DoLanguageExist(languageID))
        {
            m_currentLanguageID = languageID;
        }
        else
        {
            int indexOf_ = languageID.IndexOf('_');
            if (indexOf_ > 0)
            {
                string fallbackLangID = languageID.Substring(0, indexOf_);
                if (ReadLanguageFile(fallbackLangID) || DoLanguageExist(fallbackLangID))
                {
                    m_currentLanguageID = fallbackLangID;
                }
            }
        }
        if (string.IsNullOrEmpty(m_currentLanguageID))
        {
            m_currentLanguageID = DEFAULT_LANGUAGE_ID;

            if (!DoLanguageExist(DEFAULT_LANGUAGE_ID))
            {
                ReadLanguageFile(DEFAULT_LANGUAGE_ID);
            }
        }

        if (m_languages.ContainsKey(m_currentLanguageID))
        {
            m_currentLanguage = m_languages[m_currentLanguageID];
        }
    }
        /// <summary>
        /// Draws the localized string keys of the given LocalizedLanguage object.
        /// </summary>
        /// <param name="model">The LocalizedLanguage object</param>
        private void DrawLocalizedStrings(LocalizedLanguage model)
        {
            var numberOfKeys = script.StringKeys.Count;
            var firstIndice  = Mathf.Max(0, indiceMin - 1);
            var lastIndice   = Mathf.Min(indiceMax, numberOfKeys);
            var key          = string.Empty;

            for (var indice = firstIndice; indice < lastIndice; indice++)
            {
                try
                {
                    key = script.StringKeys[indice];
                    EditorGUILayout.BeginHorizontal();
                    if (!string.IsNullOrEmpty(key))
                    {
                        EditorGUILayout.LabelField(key, GUILayout.MaxWidth(150));
                        model.SetString(key, EditorGUILayout.TextArea(model.GetString(key), GUI.skin.textArea));
                        if (GUILayout.Button(AssetReferences.GoogleTranslateIcon, EditorStyles.label, GUILayout.Width(24), GUILayout.Height(24)))
                        {
                            AutoTranslateKeyOfLanguage(key, model);
                        }
                    }
                    EditorGUILayout.EndHorizontal();
                }
                catch
                {
                    continue;
                }
            }
        }
        private void SetOtherSettings(RTLTextMeshPro RTLTextMeshPro, LocalizedLanguage currenctLanguage)
        {
            //Set ForceFix to show number-contained texts properly
            if (currenctLanguage == LocalizedLanguage.Farsi)
            {
                RTLTextMeshPro.forceFix = true;
            }
            else
            {
                RTLTextMeshPro.forceFix = false;
            }

            //Set FontAsset and MaterialPreset to show the proper Outline
            if (FixedFontAsset)
            {
                SetFontAndMaterial((int)Outline, ref RTLTextMeshPro);
            }
            else
            {
                SetFontAndMaterial(currenctLanguage, (int)Outline, ref RTLTextMeshPro);
            }

            //Set Alignment
            if (currenctLanguage == LocalizedLanguage.Farsi && RTLTextMeshPro.alignment.ToString().Contains("Left"))
            {
                int alignmentNumber = (int)RTLTextMeshPro.alignment + 3;
                RTLTextMeshPro.alignment = (TextAlignmentOptions)alignmentNumber;
            }
            else if (currenctLanguage != LocalizedLanguage.Farsi && RTLTextMeshPro.alignment.ToString().Contains("Right"))
            {
                int alignmentNumber = (int)RTLTextMeshPro.alignment - 3;
                RTLTextMeshPro.alignment = (TextAlignmentOptions)alignmentNumber;
            }
        }
        /// <summary>
        /// Draws the localized audio clip keys of the given LocalizedLanguage object.
        /// </summary>
        /// <param name="model">The LocalizedLanguage object</param>
        private void DrawLocalizedAudioClips(LocalizedLanguage model)
        {
            var numberOfKeys = script.AudioKeys.Count;
            var firstIndice  = Mathf.Max(0, indiceMin - 1);
            var lastIndice   = Mathf.Min(indiceMax, numberOfKeys);
            var key          = string.Empty;

            for (var indice = firstIndice; indice < lastIndice; indice++)
            {
                try
                {
                    key = script.AudioKeys[indice];
                    EditorGUILayout.BeginHorizontal();
                    if (!string.IsNullOrEmpty(key))
                    {
                        EditorGUILayout.LabelField(key, GUILayout.MaxWidth(150));
                        model.SetAudio(key, (AudioClip)EditorGUILayout.ObjectField(model.GetAudio(key), typeof(AudioClip), false));
                    }
                    EditorGUILayout.EndHorizontal();
                }
                catch
                {
                    continue;
                }
            }
        }
        private void AutoTranslateAllKeyOfLanguage(LocalizedLanguage model)
        {
            var sourceModel    = script.LocalizedLanguages[0];
            var sourceLangCode = sourceModel.Language.Code();

            var targetLangCode = model.Language.Code();
            var totalSteps     = sourceModel.LocalizedStrings.Count;

            model.isBeingAutoTranslated = true;

            foreach (var keyValue in sourceModel.LocalizedStrings)
            {
                if (!string.IsNullOrEmpty(keyValue.Value))
                {
                    GoogleTranslateEditor.Translate(sourceLangCode, targetLangCode, keyValue.Value, (info) =>
                    {
                        if (info.IsValid)
                        {
                            model.SetString(keyValue.Key, info.Text);
                        }
                        else
                        {
                            Debug.LogError(string.Concat("Failed to translate the key ", keyValue.Key, " for the language ", info.TargetLanguage));
                        }
                        model.UpdateTranslationProgress(totalSteps);
                    });
                }
                else
                {
                    model.UpdateTranslationProgress(totalSteps);
                }
            }
        }
Exemple #7
0
        private void Awake()
        {
            if (Instance == null)
            {
                Instance = this;
            }

            DontDestroyOnLoad(gameObject);

            LanguageDescriptions = new DescriptionAttributes <LocalizedLanguage>().Descriptions.ToList();

            string language = PlayerPrefs.GetString("Language");

            switch (language)
            {
            case "English":
                CurrentLanguage = LocalizedLanguage.English;
                break;

            case "Farsi":
            default:
                CurrentLanguage = LocalizedLanguage.Farsi;
                break;
            }
        }
        public string Localize(LocalizedLanguage language, string key, params object[] args)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                return(null);
            }

            if (language.Responses.TryGetValue(key, out var responses))
            {
                var response = responses[_random.Next(0, responses.Length)];

                try
                {
                    return(string.Format(new CultureInfo(language.CultureCode), response, args));
                }
                catch
                {
                    return(string.Format(response, args));
                }
            }

            _logging.LogErrorAsync(
                $"Response key {key} is missing from {language.CultureCode} localization file.",
                "Localization");

            if (language.CultureCode.Equals("en-US"))
            {
                return
                    ($"Response key `{key}` was not present in one or more localization files.\n" +
                     "Please report this to the bot owner.");
            }

            return(Localize(Languages.First(x => x.CultureCode.Equals("en-US")), key, args));
        }
        /// <summary>
        /// Draws the localized contents of all created localized languages.
        /// </summary>
        /// <param name="drawElementsCallback">The function whichs will draw the localized contents when the draw area is expanded</param>
        /// <param name="drawRemoveButton">Is sets to <c>true</c> the function draw a remove button whichs allow to delete the localized language</param>
        private void DrawLocalizedContents(Action <LocalizedLanguage> drawElementsCallback, bool drawRemoveButton = false)
        {
            Rect bounds = new Rect(10, 0, splitPane.RightRect.width - 20, position.height - 0);

            GUI.Box(bounds, GUIContent.none, EditorStyles.helpBox);
            GUILayout.BeginArea(bounds);
            rightSplitScroll = GUILayout.BeginScrollView(rightSplitScroll);

            if (script.LanguageCount < NumberOfAvailableLanguage)
            {
                EditorGUILayout.BeginHorizontal();
                if (GUILayout.Button(AssetReferences.PlusIcon, EditorStyles.label, GUILayout.Width(32), GUILayout.Height(32)))
                {
                    var l = new LocalizedLanguage();
                    l.Language = languageToAdd;
                    script.LocalizedLanguages.Add(l);
                }
                languageToAdd = (Language)EditorGUILayout.EnumPopup(languageToAdd, GUILayout.ExpandWidth(true));
                EditorGUILayout.EndHorizontal();
            }

            GUILayout.Space(10);

            var count = script.LocalizedLanguages.Count;

            for (int i = 0; i < count; i++)
            {
                localizedLanguage = script.LocalizedLanguages[i];

                if (!accordions.TryGetValue(localizedLanguage.Language, out accordion))
                {
                    accordion            = new SimpleAccordion();
                    accordion.IsExpanded = localizedLanguage.isExpanded;
                    accordion.expandStateChangeCallback = (acc) => localizedLanguage.isExpanded = acc.IsExpanded;
                    accordions.Add(localizedLanguage.Language, accordion);
                }

                accordion.drawHeaderCallback = () => { return(DrawLocalizedLanguageHeader(localizedLanguage, i, count, drawRemoveButton)); };


                if (script.LocalizedLanguages.Count(item => item.Language == localizedLanguage.Language) > 1)
                {
                    EditorGUILayout.HelpBox(Strings.LanguageDuplication, MessageType.Error);
                }

                accordion.drawCallback = () =>
                {
                    GUILayout.Space(15);
                    drawElementsCallback.Invoke(localizedLanguage);
                };

                accordion.OnGUI(EditorStyles.helpBox);
            }

            GUILayout.EndScrollView();
            GUILayout.EndArea();
        }
Exemple #10
0
        private void OnLanguageChangedListener()
        {
            LocalizedLanguage newLocalizedLanguage = ISILocalization.Instance.LocalizedLanguages.SingleOrDefault(language => language.Language == ISILocalization.CurrentLanguage);
            Texture2D         flagTexture          = newLocalizedLanguage.Flag;

            _imageLanguage.sprite = Sprite.Create(flagTexture, _imageLanguage.sprite.rect, _imageLanguage.sprite.pivot);
            Settings.Language     = ISILocalization.CurrentLanguage;
            Settings.SaveSettings();
        }
Exemple #11
0
 public AdminCommandContext(CachedUserMessage message, string prefix, LocalizedLanguage language, IServiceProvider provider)
     : base(provider)
 {
     _localization = provider.GetRequiredService <LocalizationService>();
     Client        = provider.GetRequiredService <DiscordClient>();
     Message       = message;
     Prefix        = prefix;
     Database      = new AdminDatabaseContext(provider);
     Language      = language;
 }
Exemple #12
0
 private AdminCommandContext(LocalizedLanguage language, IServiceProvider provider, CachedUser user,
                             CachedGuild guild, CachedUserMessage message, ICachedMessageChannel channel)
     : base(provider)
 {
     User     = user;
     Guild    = guild;
     Message  = message;
     Channel  = channel;
     Database = new AdminDatabaseContext(provider);
     Language = language;
 }
 public AdminCommandContext(SocketUserMessage message, string prefix, LocalizedLanguage langage, IServiceProvider provider)
 {
     _localization = provider.GetRequiredService <LocalizationService>();
     Client        = provider.GetRequiredService <DiscordSocketClient>();
     User          = message.Author;
     Guild         = (message.Channel as SocketGuildChannel)?.Guild;
     Message       = message;
     Channel       = message.Channel;
     IsPrivate     = message.Channel is IPrivateChannel;
     Prefix        = prefix;
     Language      = langage;
     Database      = new AdminDatabaseContext(provider);
 }
Exemple #14
0
        public FontAssetDetails GetFontAssetDetailsByLanguage(LocalizedLanguage language)
        {
            switch (language)
            {
            case LocalizedLanguage.English:
                return(EnglishFontAssetDetails);

            case LocalizedLanguage.Farsi:
                return(FarsiFontAssetDetails);

            default:
                return(null);
            }
        }
Exemple #15
0
            public async ValueTask <AdminCommandResult> SetLanguageAsync([Remainder] LocalizedLanguage newLanguage)
            {
                var guild = await Context.Database.GetOrCreateGuildAsync(Context.Guild.Id);

                guild.Language = newLanguage;
                Context.Database.Guilds.Update(guild);
                await Context.Database.SaveChangesAsync();

                Context.Language = newLanguage;

                CommandHandler.UpdateLanguage(Context.Guild.Id, newLanguage);

                return(CommandSuccessLocalized("guild_language_set", args:
                                               $"{Markdown.Bold(guild.Language.NativeName)} ({guild.Language.EnglishName}, `{guild.Language.CultureCode}`)"));
            }
    private void Start()
    {
        string language = PlayerPrefs.GetString("Language");

        switch (language)
        {
        case "English":
            CurrentLanguage = LocalizedLanguage.English;
            break;

        case "Farsi":
        default:
            CurrentLanguage = LocalizedLanguage.Farsi;
            break;
        }
    }
    public void SetFontAndMaterial(LocalizedLanguage language, int textTypeIndex, ref RTLTextMeshPro RTLTextMeshPro)
    {
        switch (language)
        {
        case LocalizedLanguage.English:
            RTLTextMeshPro.font = EnglishFontAsset;
            RTLTextMeshPro.fontSharedMaterial = EnglishMaterialPresets[textTypeIndex];
            break;

        case LocalizedLanguage.Farsi:
        default:
            RTLTextMeshPro.font = FarsiFontAsset;
            RTLTextMeshPro.fontSharedMaterial = FarsiMaterialPresets[textTypeIndex];
            break;
        }
    }
Exemple #18
0
        public LocalizedLanguage Import(ILanguageDefinition languageDefinition, IPluginConfig config)
        {
            var language            = new LocalizedLanguage(languageDefinition);
            var workbook            = new XLWorkbook(language.Path);
            var worksheet           = workbook.Worksheet(1);
            int headerRowsRemaining = config.GetInt("numberOfHeaderRows", 1);
            int keyColumn           = 1 + config.GetInt("keyColumn", 0);
            int descriptionColumn   = 1 + config.GetInt("descriptionColumn", 1);
            int valueMasterColumn   = 1 + config.GetInt("valueColumnForMaster", 2);
            int valueNormalColumn   = 1 + config.GetInt("valueColumnForNormal", 3);

            bool isMasterLanguage = language.IsMasterLanguage;
            int  rowNumber        = 1;

            foreach (var row in worksheet.Rows())
            {
                if (headerRowsRemaining > 0)
                {
                    headerRowsRemaining--;

                    rowNumber++;
                    continue;
                }

                if (row.IsEmpty())
                {
                    rowNumber++;
                    continue;
                }

                int valueColumn = language.IsMasterLanguage ? valueMasterColumn : valueNormalColumn;

                language.AddText(
                    key: row.Cell(keyColumn).Value.ToString(),
                    description: row.Cell(descriptionColumn).Value.ToString(),
                    value: row.Cell(valueColumn).Value.ToString(),
                    rowNumber: rowNumber);

                rowNumber++;
            }

            return(language);
        }
Exemple #19
0
        public void ChangeLanguage(string language)
        {
            if (language == CurrentLanguage.ToString())
            {
                return;
            }
            PlayerPrefs.SetString("Language", language);
            switch (language)
            {
            case "Farsi":
                CurrentLanguage = LocalizedLanguage.Farsi;
                break;

            case "English":
                CurrentLanguage = LocalizedLanguage.English;
                break;
            }
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        }
        public Task SendTargetRevocationEmbedAsync(RevocablePunishment punishment, IUser target,
                                                   LocalizedLanguage language)
        {
            var typeName = punishment.GetType().Name.ToLower();
            var builder  = new LocalEmbedBuilder().WithWarnColor()
                           .WithTitle(_localization.Localize(language, $"punishment_{typeName}") +
                                      $" - {_localization.Localize(language, "punishment_case", punishment.Id)}")
                           .WithDescription(_localization.Localize(language, $"punishment_{typeName}_revoke_description", Markdown.Bold(_client.GetGuild(punishment.GuildId).Name.Sanitize())))
                           .AddField(_localization.Localize(language, "title_reason"),
                                     punishment.RevocationReason ?? _localization.Localize(language, "punishment_noreason"))
                           .WithTimestamp(punishment.RevokedAt ?? DateTimeOffset.UtcNow);

            if (punishment is Mute channelMute && channelMute.ChannelId.HasValue)
            {
                builder.AddField(_localization.Localize(language, "punishment_mute_channel"),
                                 _client.GetGuild(punishment.GuildId).GetTextChannel(channelMute.ChannelId.Value).Mention);
            }

            return(target.SendMessageAsync(embed: builder.Build()));
        }
Exemple #21
0
        public static string GetLocalizedValue(string key, LocalizedLanguage language)
        {
            if (!IsInitialized)
            {
                Initialize();
            }

            string value = "";

            switch (language)
            {
            case LocalizedLanguage.Farsi:
                LocalizedFarsiTexts.TryGetValue(key, out value);
                break;

            case LocalizedLanguage.English:
                LocalizedEnglishTexts.TryGetValue(key, out value);
                break;
            }
            return(value);
        }
    private bool ReadLanguageFile(string languageId)
    {
        string    fileName         = BASEFILENAME + languageId + FILEEXTENSION;
        string    templateFileName = Path.Combine(FILEFOLDER, Path.GetFileNameWithoutExtension(fileName));
        TextAsset asset            = ((TextAsset)Resources.Load(templateFileName));

        if (asset != null)
        {
            string            fileJSON    = asset.text;
            LocalizedLanguage newLanguage = new LocalizedLanguage();

            try
            {
                Hashtable data = JSON.JsonDecode(fileJSON) as Hashtable;
                newLanguage.ParseJsonData(data);
            }
            catch (Exception je)
            {
                UnityEngine.Debug.Log("The text file is not in JSON format, " + je.ToString());
            }

            if (m_languages.ContainsKey(newLanguage.ID))
            {
                if (newLanguage.Version > m_languages[newLanguage.ID].Version)
                {
                    m_languages.Remove(newLanguage.ID);
                    m_languages.Add(newLanguage.ID, newLanguage);
                    return(true);
                }
            }
            else
            {
                m_languages.Add(newLanguage.ID, newLanguage);
                return(true);
            }
        }

        return(false);
    }
        private void SetTextValue(int languageIndex, bool editMode = false)
        {
            RTLTextMeshPro RTLTextMeshPro = GetComponent <RTLTextMeshPro>();

            if (RTLTextMeshPro == null)
            {
                return;
            }

            LocalizedLanguage currenctLanguage = (LocalizedLanguage)languageIndex;

            if (!string.IsNullOrEmpty(LocalizedString.key))
            {
                string value;
                if (editMode)
                {
                    value = LocalizationManager.GetLocalizedValue(LocalizedString.key, currenctLanguage);
                }
                else
                {
                    value = LocalizedString.value;
                }

                if (!string.IsNullOrEmpty(value))
                {
                    if (!IsContainsAtSign)
                    {
                        value = value.Replace("@", System.Environment.NewLine);
                    }
                    RTLTextMeshPro.text = value;
                }
            }

            SetOtherSettings(RTLTextMeshPro, currenctLanguage);

            //Re-Fix
            RTLTextMeshPro.UpdateText();
        }
        private void AutoTranslateKeyOfLanguage(string key, LocalizedLanguage model)
        {
            var sourceLang     = script.LocalizedLanguages[0];
            var sourceLangCode = sourceLang.Language.Code();

            var sourceText     = sourceLang.GetString(key);
            var targetLangCode = model.Language.Code();

            if (!string.IsNullOrEmpty(sourceText))
            {
                GoogleTranslateEditor.Translate(sourceLangCode, targetLangCode, sourceText, (info) =>
                {
                    if (info.IsValid)
                    {
                        model.SetString(key, info.Text);
                    }
                    else
                    {
                        Debug.LogError("Failed to translate the key " + key);
                    }
                });
            }
        }
        public void OnGUI()
        {
            EditorGUILayout.BeginHorizontal("Box");
            EditorGUILayout.LabelField("Search: ", EditorStyles.boldLabel, GUILayout.MaxWidth(47));
            value = EditorGUILayout.TextField(value);
            EditorGUILayout.EndHorizontal();

            value ??= "";

            EditorGUILayout.BeginVertical();
            scroll = EditorGUILayout.BeginScrollView(scroll);

            foreach (var kvp in LocalizedLanguage.Localization.Where(kvp => kvp.Key.ToLower().Contains(value.ToLower()) || kvp.Value.ToLower().Contains(value.ToLower())))
            {
                EditorGUILayout.BeginHorizontal("Box");
                var deleteIcon = Resources.Load <Texture>("LocalizationEditorTextures/Delete");
                var content    = new GUIContent(deleteIcon);

                if (GUILayout.Button(content, GUILayout.MaxWidth(20), GUILayout.MaxHeight(20)))
                {
                    if (EditorUtility.DisplayDialog($"Remove key '{kvp.Key}'", $"This will remove '{kvp.Key}' from the localization", "Sure", "Cancel"))
                    {
                        Localization.Remove(kvp.Key);
                        Localization.UpdateLocalization();
                        LocalizedLanguage = Localization.CurrentLocalizedLanguage;
                    }
                }

                EditorGUILayout.TextField(kvp.Key);
                EditorGUILayout.LabelField(kvp.Value);
                EditorGUILayout.EndHorizontal();
            }

            EditorGUILayout.EndScrollView();
            EditorGUILayout.EndVertical();
        }
Exemple #26
0
        public static string HumanizeFormatted(this TimeSpan ts, LocalizationService localization,
                                               LocalizedLanguage language, TimeUnit?minimum = null, bool ago = false)
        {
            var min    = minimum ?? TimeUnit.Minute;
            var format = ts.Humanize(10, language.Culture, minUnit: min, maxUnit: TimeUnit.Year);

            if (!ago)
            {
                return(format);
            }

            var belowMinimum = false;

            switch (minimum)
            {
            case TimeUnit.Second:
                belowMinimum = ts < TimeSpan.FromSeconds(1);
                break;

            case TimeUnit.Minute:
                belowMinimum = ts < TimeSpan.FromMinutes(1);
                break;

            case TimeUnit.Hour:
                belowMinimum = ts < TimeSpan.FromHours(1);
                break;

            case TimeUnit.Day:
                belowMinimum = ts < TimeSpan.FromDays(1);
                break;
            }

            return(belowMinimum
                ? localization.Localize(language, "info_now")
                : localization.Localize(language, "info_ago", format));
        }
        private string Load()
        {
            var type = PrefabUtility.GetPrefabType(script.gameObject);

            if (type != PrefabType.None && type != PrefabType.PrefabInstance)
            {
                return(Strings.ImportError);
            }

            XmlDocument doc          = null;
            XmlNode     resourceNode = null;
            string      path         = string.Empty;
            string      key          = string.Empty;
            string      value        = string.Empty;

            bool hasError    = false;
            bool isFirstFile = true;

            List <string>            keyList           = new List <string>();
            List <LocalizedLanguage> existingLanguages = new List <LocalizedLanguage>();

            List <StringKV>   keyValues;
            LocalizedLanguage currentLoadedLanguage;

            foreach (var language in LanguageEnumNames)
            {
                path = Path.Combine(Application.dataPath, string.Format(ISILocalization.LanguagePaths, language));

                if (File.Exists(path))
                {
                    keyValues = new List <StringKV>();
                    doc       = new XmlDocument();
                    using (var stream = new FileStream(path, FileMode.Open))
                    {
                        doc.Load(stream);
                        stream.Close();
                    }
                    // get all xml nodes child of the node 'resources'
                    resourceNode = doc["resources"];
                    var index = 1;

                    // remove xml comments
                    var children = resourceNode.ChildNodes.Cast <XmlNode>().Where(n => n.NodeType != XmlNodeType.Comment);

                    foreach (XmlNode node in children)
                    {
                        key   = node.Attributes[0].Value;
                        value = node.FirstChild == null ? "" : node.FirstChild.Value;

                        keyValues.Add(new StringKV(key, value));

                        if (isFirstFile)
                        {
                            keyList.Add(key);
                        }

                        error = CodeGenerationUtils.CheckIdentifier(key);
                        if (error != null)
                        {
                            hasError = true;
                            Debugger.LogError(string.Format(Strings.InvalidKeyName, key));
                        }
                        index++;
                    }
                    isFirstFile                    = false;
                    currentLoadedLanguage          = new LocalizedLanguage(keyValues);
                    currentLoadedLanguage.Language = (Language)Enum.Parse(typeof(Language), language);
                    existingLanguages.Add(currentLoadedLanguage);
                }
            }

            if (keyList.Any())
            {
                if (!hasError)
                {
                    script.StringKeys.Clear();

                    foreach (var k in keyList)
                    {
                        script.StringKeys.Add(k);
                    }
                    foreach (var language in existingLanguages)
                    {
                        script.ReplaceLocalizedLanguage(language);
                    }

                    Generate();

                    PrefabUtility.CreatePrefab(ISILocalization.PrefabPath, script.gameObject);
                    AssetDatabase.Refresh();

                    return(Strings.Updated);
                }
                else
                {
                    return(Strings.CheckErrors);
                }
            }
            else
            {
                return(Strings.MissingLanguage);
            }
        }
        private Rect DrawLocalizedLanguageHeader(LocalizedLanguage language, int index, int languagesCount, bool drawRemoveButton = false)
        {
            var icon = accordion.IsExpanded ? FA.angle_double_down : FA.angle_double_right;

            var rect = EditorGUILayout.BeginVertical();

            var boxTitle = new GUIContent(language.LanguageName);

            GUILayout.Box(boxTitle, AssetReferences.AccordionHeader, GUILayout.ExpandWidth(true), GUILayout.Height(20));

            DrawerHelper.FAIcon(rect, icon, FAOption.TextAnchor(TextAnchor.UpperLeft), FAOption.FontSize(20), FAOption.Padding(new RectOffset(5, 0, 0, 0)));

            EditorGUILayout.BeginHorizontal();

            GUILayout.Space(100);
            // draw translation progress bar
            if (language.isBeingAutoTranslated)
            {
                var r = GUILayoutUtility.GetRect(250, 32);
                EditorGUI.ProgressBar(r, language.translationProgress, string.Empty);
            }

            GUILayout.FlexibleSpace();

            // draw google translate button
            if (index > 0 && selectedTab == 0)
            {
                if (GUI.Button(new Rect(rect.width - 82, rect.y, 24, rect.height), AssetReferences.GoogleTranslateIcon, EditorStyles.label))
                {
                    AutoTranslateAllKeyOfLanguage(language);
                }
            }

            GUILayout.Space(10);

            // draw up arrow
            if (index > 0 && DrawerHelper.FAButton(new Rect(rect.width - 58, rect.y, 24, rect.height), FA.arrow_up))
            {
                SwapLanguagesPosition(index, index - 1);
            }

            GUILayout.Space(10);

            // draw down arrao
            if (index < languagesCount - 1 && DrawerHelper.FAButton(new Rect(rect.width - 34, rect.y, 24, rect.height), FA.arrow_down))
            {
                SwapLanguagesPosition(index, index + 1);
            }

            GUILayout.Space(10);

            // draw remove button
            if (drawRemoveButton && DrawerHelper.FAButton(new Rect(rect.width - 10, rect.y, 24, rect.height), FA.trash, FAOption.TextColor(Color.red)))
            {
                script.LocalizedLanguages.Remove(language);
            }

            EditorGUILayout.EndHorizontal();

            EditorGUILayout.EndVertical();

            return(rect);
        }
        public LocalEmbedFieldBuilder FormatAdditionalPunishment(Punishment punishment, LocalizedLanguage language)
        {
            var field = new LocalEmbedFieldBuilder()
                        .WithName(_localization.Localize(language, "punishment_warning_additional"));

            switch (punishment)
            {
            case Kick _:
                field.WithValue(_localization.Localize(language, "punishment_kick") + $" (#{punishment.Id}) ");
                break;

            case Ban ban:
                field.WithValue(_localization.Localize(language, "punishment_ban") + $" (#{punishment.Id}) " +
                                $" ({(ban.Duration.HasValue ? ban.Duration.Value.Humanize(minUnit: TimeUnit.Second, culture: language.Culture) : _localization.Localize(language, "punishment_permanent"))})");
                break;

            case Mute mute:
                field.WithValue(_localization.Localize(language, "punishment_mute") + $" (#{punishment.Id}) " +
                                $" ({(mute.Duration.HasValue ? mute.Duration.Value.Humanize(minUnit: TimeUnit.Second, culture: language.Culture) : _localization.Localize(language, "punishment_permanent"))})");
                break;
            }

            return(field);
        }
        private async Task SendTargetEmbedAsync(Punishment punishment, IUser target, Punishment additionalPunishment, LocalizedLanguage language)
        {
            var typeName = punishment.GetType().Name.ToLower();
            var builder  = new LocalEmbedBuilder().WithErrorColor()
                           .WithTitle(_localization.Localize(language, $"punishment_{typeName}") +
                                      $" - {_localization.Localize(language, "punishment_case", punishment.Id)}")
                           .AddField(_localization.Localize(language, "title_reason"),
                                     punishment.Reason ?? _localization.Localize(language, "punishment_noreason"))
                           .WithTimestamp(punishment.CreatedAt);

            if (!(additionalPunishment is null))
            {
                builder.AddField(FormatAdditionalPunishment(additionalPunishment, language));
            }

            if (punishment is Warning)
            {
                using var ctx = new AdminDatabaseContext(_provider);

                var warningCount = await ctx.Punishments.OfType <Warning>().CountAsync(x =>
                                                                                       x.TargetId == target.Id && x.GuildId == punishment.GuildId && !x.RevokedAt.HasValue);

                builder.WithDescription(_localization.Localize(language, "punishment_warning_description",
                                                               Markdown.Bold(_client.GetGuild(punishment.GuildId).Name.Sanitize()),
                                                               Markdown.Bold(warningCount.ToOrdinalWords(language.Culture))));
            }
            else
            {
                builder.WithDescription(_localization.Localize(language, $"punishment_{typeName}_description",
                                                               _client.GetGuild(punishment.GuildId).Name));
            }

            if (punishment is RevocablePunishment revocable)
            {
                var field = new LocalEmbedFieldBuilder()
                            .WithName(_localization.Localize(language, "punishment_appeal"));

                switch (revocable)
                {
                case Ban ban:
                    field.WithValue(!ban.Duration.HasValue || ban.Duration.Value > TimeSpan.FromDays(1)
                            ? GetAppealInstructions()
                            : _localization.Localize(language, "punishment_tooshort",
                                                     ban.Duration.Value.Humanize(minUnit: TimeUnit.Minute, culture: language.Culture)));
                    break;

                case Mute mute:
                    field.WithValue(!mute.Duration.HasValue || mute.Duration.Value > TimeSpan.FromDays(1)
                            ? GetAppealInstructions()
                            : _localization.Localize(language, "punishment_tooshort",
                                                     mute.Duration.Value.Humanize(minUnit: TimeUnit.Minute, culture: language.Culture)));
                    break;

                default:
                    field = null;
                    break;
                }

                if (!(field is null))
                {
                    builder.AddField(field);
                }

                string GetAppealInstructions()
                {
                    return(_localization.Localize(language, "punishment_appeal_instructions",
                                                  Markdown.Code(punishment.Id.ToString()),
                                                  Markdown.Code($"{_config.DefaultPrefix}appeal {punishment.Id} [{_localization.Localize(language, "title_reason").ToLower()}]")));
                }
            }

            if (punishment is Mute channelMute && channelMute.ChannelId.HasValue)
            {
                builder.AddField(_localization.Localize(language, "punishment_mute_channel"),
                                 _client.GetGuild(punishment.GuildId).GetTextChannel(channelMute.ChannelId.Value).Mention);
            }

            if (punishment.Format != ImageFormat.Default)
            {
                builder.WithImageUrl($"attachment://attachment.{punishment.Format.ToString().ToLower()}");
                _ = target.SendMessageAsync(new LocalAttachment(punishment.Image,
                                                                $"attachment.{punishment.Format.ToString().ToLower()}"), embed: builder.Build());

                return;
            }

            _ = target.SendMessageAsync(embed: builder.Build());
        }