using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using MongoDB.Driver; using MongoDB.Driver.Linq; using Newtonsoft.Json; using Sony.ChartBot.Entities.Storage; namespace Sony.ChartBot.Repository { public class CountryRepository : BaseRepository { private IDictionary SupportedCountries { get; } public CountryRepository() : this(DbConstants.Database) { } public CountryRepository(IDictionary supportedCountries) : this(supportedCountries, DbConstants.Database) { } public CountryRepository(string database) : base(database, DbConstants.CountrySettingsCollection) { SupportedCountries = GetCountriesFromEmbededResource(); } public CountryRepository(IDictionary supportedCountries, string database) : base(database, DbConstants.CountrySettingsCollection) { SupportedCountries = supportedCountries; } public virtual SupportedCountry FindSupportedCountry(string input) { return GetSupportedCountry(input) ?? SupportedCountries.Values.FirstOrDefault(c => string.Equals(c.EnglishName, input, StringComparison.InvariantCultureIgnoreCase) || string.Equals(c.Emoji, input) || (c.Synonyms != null && c.Synonyms.Any(s => string.Equals(s, input, StringComparison.InvariantCultureIgnoreCase))) ); } public virtual SupportedCountry GetSupportedCountry(string countryCode) { if (!SupportedCountries.ContainsKey(countryCode.ToLowerInvariant())) { return null; } return SupportedCountries[countryCode.ToLowerInvariant()]; } public virtual SupportedCountry GetGlobalCountry() { return GetSupportedCountry("global"); } public virtual async Task GetCountrySettingAsync(string userId) { return await Collection.AsQueryable().FirstOrDefaultAsync(c => c.UserId == userId); } public virtual async Task> GetCountrySettingsAsync() { return await Collection.AsQueryable().ToListAsync(); } public virtual async Task GetDefaultCountryAsync(string userId) { var setting = await GetCountrySettingAsync(userId); if (setting == null) { return null; } return GetSupportedCountry(setting.CountryCode); } public virtual async Task SetDefaultCountryAsync(string userId, SupportedCountry country, int timeZoneDiffUtc) { var filter = Builders.Filter.Eq(nameof(CountrySetting.UserId), userId); await Collection.ReplaceOneAsync(filter, new CountrySetting { UserId = userId, CountryCode = country.CountryCode, TimezoneDiffUtc = timeZoneDiffUtc }, new UpdateOptions { IsUpsert = true }); } private IDictionary GetCountriesFromEmbededResource() { using (var stream = Assembly.GetExecutingAssembly() .GetManifestResourceStream("Sony.ChartBot.Repository.countries.json")) { if (stream != null) { using (var reader = new StreamReader(stream)) { var countries = (IEnumerable) new JsonSerializer().Deserialize(reader, typeof(IEnumerable)); return countries.ToDictionary(c => c.CountryCode.ToLowerInvariant()); } } } throw new Exception("Failed finding country data"); } } }