using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using UnityEditor; using UnityEngine; using Crowdin.Plugin.Helpers; using Crowdin.Plugin.Helpers.PluginLocalization; using Crowdin.Plugin.Models; using Crowdin.Plugin.Models.Settings; using Crowdin.Plugin.Server_API; using Crowdin.Plugin.Server_API.Helpers; using Crowdin.Plugin.Server_API.Models.Branches; using Crowdin.Plugin.Server_API.Services; namespace Crowdin.Editor { public class BranchSelector : IDisposable { private int currentIndex = 0; private string[] branches = { "main" }; private Dictionary branchIds = new(); private readonly List rawSettings; private readonly CancellationToken ownerLifetime; public static BranchSelector CreateAndLoadSettings(CancellationToken ownerLifetime) { return new BranchSelector(SettingsHelper.GetBranchesList(), ownerLifetime); } private BranchSelector(List entries, CancellationToken ownerLifetime) { if (entries is not null && entries.Count > 0) { branches = entries.Select(entry => entry.name).ToArray(); branchIds = entries.ToDictionary(data => data.name, data => data.id); } rawSettings = entries; this.ownerLifetime = ownerLifetime; } public void DrawLayout() { GUILayout.BeginHorizontal("box"); GUILayout.Label(LocalizationHelper.GetLocalStringByKey(LocalKeys.list_branches)); currentIndex = EditorGUILayout.Popup(currentIndex, branches); if (GUILayout.Button(LocalizationHelper.GetLocalStringByKey(LocalKeys.button_branches_refresh))) { RefreshBranchesList(); } GUILayout.EndHorizontal(); } public void RefreshBranchesList() { RefreshBranchesListAsync().Forget(); } private async Task RefreshBranchesListAsync() { try { var service = new BranchApiService(); Debug.Log("Refreshing branches list..."); List remoteBranches = await service.ListBranches(ownerLifetime); Debug.Log($"Branches list: received {remoteBranches.Count}"); branches = remoteBranches.Select(branch => branch.Name).ToArray(); branchIds = remoteBranches.ToDictionary(branch => branch.Name, branch => branch.Id); } catch (CrowdinApiException ex) { Debug.LogException(ex); } } public int? GetSelectedBranchId() { return branchIds.TryGetValue(branches[currentIndex], out int branchId) ? branchId : null; } public void SaveSettings() { rawSettings.Clear(); foreach (string branchName in branches) { if (!branchIds.TryGetValue(branchName, out int branchId)) { continue; } var entry = new CachedBranchData { id = branchId, name = branchName }; rawSettings.Add(entry); } } public void Dispose() { SaveSettings(); } } }