using System; using System.Globalization; using game; using JetBrains.Annotations; using UniRx; public class DailyReward : ITimeReward { public bool IsAvailable => _enterTime != null; //TODO: to reactive public int DayIndex { get; private set; } = 0; public int DaysCount => _rewards.days.Count; private DateTime _lastEntryTime = default; private DateTime _nextRewardTime = default; private readonly ConfDailyReward _rewards; private DateTime? _enterTime = null; public DailyReward(ConfDailyReward conf) { _rewards = conf; NetTime.Instance.IsAvailableAsObservable() .Subscribe(x => { _enterTime = x ? (DateTime?)NetTime.Instance.Time : null; }); } private bool HasRewardNotReceived() { return _enterTime >= _nextRewardTime || DayIndex <= 0; } public ConfRewardItem GetItemForTheDay(int day) { ConfDailyRewardDay dailyReward = _rewards.days[day]; ConfDailyRewardItemsCollection itemsCollection = dailyReward.items; for (var i = 0; i < itemsCollection.uniqueItems.Count; i++) { var rewardItem = itemsCollection.uniqueItems[i]; if (global::Save.Inventory.IsPurchasedItem(rewardItem.item.protoId) == false) return rewardItem; } return itemsCollection.reserveItem; } public bool TryGetReward([CanBeNull] out ConfRewardItem reward) { reward = null; if (RewardIsWasted()) { ResetReward(); return false; } if (HasRewardNotReceived()) reward = GetItemForTheDay(DayIndex); else return false; return reward != null; } private void ResetReward() { DayIndex = 0; ResetTime(); } private void ResetTime() { _lastEntryTime = NetTime.Instance.Time; _nextRewardTime = _lastEntryTime.AddHours(24); } public void Load(DataGame data) { DayIndex = (int)data.timeRewards.daily.dayIndex; if (string.IsNullOrEmpty(data.timeRewards.daily.lastEntryTime)) { ResetTime(); } else { _lastEntryTime = DateTime.Parse(data.timeRewards.daily.lastEntryTime); _nextRewardTime = DateTime.Parse(data.timeRewards.daily.nextRewardTime); } } private bool RewardIsWasted() { if (IsAvailable == false) return false; DateTime currentTime = (DateTime)_enterTime; DateTime nextRewardTime = _nextRewardTime; double current = currentTime.ToStamp(); double next = nextRewardTime.ToStamp(); return current - next > 60 * 60 * 24; } public void Save(DataGame data) { data.timeRewards.daily.dayIndex = (uint) DayIndex; data.timeRewards.daily.lastEntryTime = _lastEntryTime.ToString(CultureInfo.InvariantCulture); data.timeRewards.daily.nextRewardTime = _nextRewardTime.ToString(CultureInfo.InvariantCulture); } }