using System;
using System.Collections.Generic;
using LitJson;
using UnityEngine;

namespace Wizard;

public class AvatarBattleAllInfo
{
	public class PeriodData
	{
		public DateTime BeginTime = DateTime.MaxValue;

		public DateTime EndTime = DateTime.MinValue;

		public double StartUnixTime { get; set; }

		public double EndUnixTime { get; set; }
	}

	private Dictionary<string, AvatarBattleInfo> _avatarBattleDictionary = new Dictionary<string, AvatarBattleInfo>();

	public PeriodData FreeMatchPeriod = new PeriodData();

	public PeriodData GatheringPeriod = new PeriodData();

	private bool _avatarBattleScheduleExist;

	private float _receiveSinceTime;

	private double _receiveServerUnixTime;

	public List<AvatarBattleInfo> AvatarBattleInfoList { get; } = new List<AvatarBattleInfo>();

	public bool IsWithinFreeMatchPeriod => IsWithinPeriod(FreeMatchPeriod);

	public bool IsWithinGatheringPeriod => IsWithinPeriod(GatheringPeriod);

	public void Parse(JsonData json, JsonData headerData)
	{
		JsonData jsonData = json["abilities"];
		foreach (string key in jsonData.Keys)
		{
			AvatarBattleInfo avatarBattleInfo = new AvatarBattleInfo(jsonData[key]);
			_avatarBattleDictionary[avatarBattleInfo.LeaderSkinId] = avatarBattleInfo;
			avatarBattleInfo.SetAbility(jsonData[avatarBattleInfo.LeaderSkinId]);
			AvatarBattleInfoList.Add(avatarBattleInfo);
		}
		JsonData jsonData2 = json["schedules"];
		if (jsonData2.IsObject)
		{
			if (jsonData2.TryGetValue("free_battle", out var value))
			{
				SetPeriodData(FreeMatchPeriod, value);
				_avatarBattleScheduleExist = true;
				_receiveSinceTime = Time.realtimeSinceStartup;
				_receiveServerUnixTime = headerData["servertime"].ToDouble();
			}
			if (jsonData2.TryGetValue("gathering", out var value2))
			{
				SetPeriodData(GatheringPeriod, value2);
				_avatarBattleScheduleExist = true;
				_receiveSinceTime = Time.realtimeSinceStartup;
				_receiveServerUnixTime = headerData["servertime"].ToDouble();
			}
		}
	}

	public AvatarBattleInfo Get(string id)
	{
		if (string.IsNullOrEmpty(id))
		{
			return null;
		}
		if (_avatarBattleDictionary.TryGetValue(id, out var value))
		{
			return value;
		}
		return null;
	}

	private void SetPeriodData(PeriodData period, JsonData jsonData)
	{
		period.BeginTime = DateTime.Parse(jsonData["begin_time"].ToString());
		period.EndTime = DateTime.Parse(jsonData["end_time"].ToString());
		period.StartUnixTime = ConvertTime.DateTimeToUnixTime(DateTime.Parse(jsonData["begin_time"].ToString()));
		period.EndUnixTime = ConvertTime.DateTimeToUnixTime(DateTime.Parse(jsonData["end_time"].ToString()));
	}

	private bool IsWithinPeriod(PeriodData period)
	{
		if (!_avatarBattleScheduleExist)
		{
			return false;
		}
		double num = _receiveServerUnixTime + (double)Time.realtimeSinceStartup - (double)_receiveSinceTime;
		if (num > period.EndUnixTime)
		{
			return false;
		}
		return num > period.StartUnixTime;
	}
}
