using System;
using System.Collections.Generic;
using System.Linq;
using Cute;
using UnityEngine;

namespace Wizard;

public class Chat : UIBase
{
	public enum eRequestDirection
	{
		OLD = 1,
		NEW,
		BOTH
	}

	private const int MAX_PAST_MESSAGE_REQUEST = 30;

	private int _pastMessageRequestCnt;

	private IChatSettings _chatSettings;

	[SerializeField]
	private ChatConnectController _chatConnectController;

	[SerializeField]
	private ChatLogUI _chatLogUI;

	[SerializeField]
	private ChatSendTextUI _chatSendTextUI;

	[SerializeField]
	private ChatSendStampUI _sendStampUI;

	[SerializeField]
	private UIEventListener _sendUICloseArea;

	[SerializeField]
	private RewardBase _rewardBase;

	private bool _isPastLogComplete;

	private int _pastVisibleMessageCnt;

	private bool _isInitComplete;

	public Action<ChatInfo> OnAddNewChatMessage { get; set; }

	public Action<List<string>> OnMissionCleared { get; set; }

	public void Init(IChatSettings chatSettings, List<IChatActionUI> chatActionUIList, List<int> stampList, NetworkDefine.MAINTENANCE_TYPE maintenanceType, Action<ChatInfo> OnFinish)
	{
		_chatSettings = chatSettings;
		_chatConnectController.Init(PollingChatLog, OnConnectResultError);
		_chatSendTextUI.Init(SendTextMessage, OnOpenTextInputUI, OnCloseTextInputUI);
		UIManager.SetObjectToGrey(_chatSendTextUI.gameObject, Data.MaintenanceCodeList.Contains(maintenanceType));
		_sendStampUI.Init(SendStamp, OnOpenStampUI, OnCloseStampUI, stampList);
		_chatLogUI.Init(chatSettings, _chatConnectController, stampList);
		foreach (IChatActionUI chatActionUI in chatActionUIList)
		{
			chatActionUI.Init(_chatSettings, _chatConnectController, _chatLogUI, AddNewChatLogAfterSendChat);
		}
		UIEventListener sendUICloseArea = _sendUICloseArea;
		sendUICloseArea.onClick = (UIEventListener.VoidDelegate)Delegate.Combine(sendUICloseArea.onClick, (UIEventListener.VoidDelegate)delegate
		{
			_chatSendTextUI.CloseInputUI(isClearText: false);
			_sendStampUI.CloseStampList();
		});
		StartConnectChatInfo(delegate(ChatInfo chatInfo)
		{
			_isInitComplete = true;
			OnFinish.Call(chatInfo);
		});
	}

	public void ReadyClose()
	{
		_chatConnectController.Close();
	}

	public void ExecuteClose()
	{
		_chatLogUI.CloseChatLogView();
		UnityEngine.Object.Destroy(base.gameObject);
	}

	private void OnConnectResultError()
	{
		UIManager.GetInstance().CloseNotLatestDialogAll();
		_chatLogUI.CloseDeckView();
	}

	private void OnOpenTextInputUI(ChatOpenCloseAnimation openCloseAnim)
	{
		_sendStampUI.CloseStampList();
		_chatLogUI.ChangeLogViewSizeByInputUIAnimation(openCloseAnim);
	}

	private void OnCloseTextInputUI(ChatOpenCloseAnimation openCloseAnim)
	{
		if (!_sendStampUI.IsOpen)
		{
			_chatLogUI.ChangeLogViewSizeByInputUIAnimation(openCloseAnim);
		}
	}

	private void SendTextMessage(string text)
	{
		ChatPostTask chatPostTask = new ChatPostTask(_chatSettings.ApiSettings.ApiChatPost);
		chatPostTask.SetParameter(0, text);
		_chatConnectController.StartConnectCommon(chatPostTask, delegate
		{
			_chatConnectController.PausePolling();
			_chatSendTextUI.CloseInputUI(isClearText: true, delegate
			{
				AddNewChatLogAfterSendChat();
				_chatConnectController.ResumePolling();
			});
		});
	}

	private void OnOpenStampUI(ChatOpenCloseAnimation openCloseAnim)
	{
		_chatSendTextUI.CloseInputUI(isClearText: false);
		_chatLogUI.ChangeLogViewSizeByInputUIAnimation(openCloseAnim);
	}

	private void OnCloseStampUI(ChatOpenCloseAnimation openCloseAnim)
	{
		if (!_chatSendTextUI.IsOpen)
		{
			_chatLogUI.ChangeLogViewSizeByInputUIAnimation(openCloseAnim);
		}
	}

	private void SendStamp(int id)
	{
		ChatPostTask task = new ChatPostTask(_chatSettings.ApiSettings.ApiChatPost);
		task.SetParameter(1, id.ToString());
		_chatConnectController.StartConnectCommon(task, delegate
		{
			_chatConnectController.PausePolling();
			_sendStampUI.CloseStampList(delegate
			{
				AddNewChatLogAfterSendChat();
				_chatConnectController.ResumePolling();
			});
			if (task.AchievedInfo != null && task.AchievedInfo._rewards.Count > 0)
			{
				UIManager.GetInstance().createInSceneCenterLoading();
				DialogBase dialogBase = UIManager.GetInstance().CreateDialogClose();
				dialogBase.SetSize(DialogBase.Size.M);
				dialogBase.SetTitleLabel(Data.SystemText.Get("Story_0029"));
				dialogBase.SetButtonLayout(DialogBase.ButtonLayout.OkBtn);
				RewardBase component = NGUITools.AddChild(dialogBase.gameObject, _rewardBase.gameObject).GetComponent<RewardBase>();
				for (int num = 0; num < task.AchievedInfo._rewards.Count; num++)
				{
					component.AddReward(task.AchievedInfo._rewards[num]);
				}
				List<string> messages = new List<string>();
				for (int num2 = 0; num2 < task.AchievedInfo._missions.Count; num2++)
				{
					messages.Add(task.AchievedInfo._missions[num2].achieved_message);
				}
				dialogBase.OnClose = delegate
				{
					if (OnMissionCleared != null)
					{
						OnMissionCleared(messages);
					}
				};
				component.EndCreate();
			}
		});
	}

	private void AddNewChatLogAfterSendChat()
	{
		AddNewChatLog(delegate
		{
			_chatLogUI.MoveNewMessagePosition();
		});
	}

	private bool GetCanUpdateUI()
	{
		if (UIManager.GetInstance().isOpenDialog())
		{
			return false;
		}
		if (_chatLogUI.IsShowDeckView())
		{
			return false;
		}
		return true;
	}

	private void Update()
	{
		if (!_chatLogUI.IsEnableUpdateUI && GetCanUpdateUI())
		{
			_chatLogUI.SetEnableUpdateUI();
		}
	}

	private void PollingChatLog()
	{
		AddNewChatLog(null, isPolling: true);
	}

	private void StartConnectChatInfo(Action<ChatInfo> callbackOnSuccess)
	{
		int value = PlayerPrefsWrapper.GetValue(_chatSettings.PlayerPrefsKeyLatestReadChatMessageId);
		if (value >= 0)
		{
			CreateChatLogReadMessage(value, callbackOnSuccess);
		}
		else
		{
			CreateChatLog(callbackOnSuccess);
		}
	}

	private void CreateChatLogReadMessage(int latestMessageId, Action<ChatInfo> callbackOnSuccess)
	{
		ChatGetMessagesTask task = new ChatGetMessagesTask(_chatSettings.ApiSettings.ApiChatMessages);
		task.SetParameter(latestMessageId, eRequestDirection.BOTH, 3);
		_chatConnectController.StartConnectCommon(task, delegate
		{
			ChatInfo chatInfo = task.ChatInfo;
			_chatConnectController.UpdatePollingInterval(chatInfo.WaitInterval);
			int unreadMessageId = -1;
			List<ChatMessageInfo> visibleMessageList = chatInfo.VisibleMessageList;
			if (visibleMessageList.Count > 0)
			{
				int messageId = visibleMessageList.Last().MessageId;
				if (latestMessageId != messageId)
				{
					int num = visibleMessageList.FindIndex((ChatMessageInfo x) => x.MessageId == latestMessageId) + 1;
					if (num > 0 && visibleMessageList.Count > num)
					{
						unreadMessageId = visibleMessageList[num].MessageId;
					}
					SaveReadLatestId(messageId);
				}
			}
			_pastVisibleMessageCnt += chatInfo.VisibleMessageList.Count;
			_chatLogUI.CreateChatLogView(chatInfo.MessageList, OnInitializeOldestLog, delegate
			{
				if (CheckNeedsPastVisibleMessage(chatInfo))
				{
					AddPastChatLog(delegate
					{
						_chatLogUI.ResetScrollDefaultPosition(unreadMessageId);
						callbackOnSuccess.Call(chatInfo);
					});
				}
				else
				{
					callbackOnSuccess.Call(chatInfo);
				}
			}, unreadMessageId);
		});
	}

	private void CreateChatLog(Action<ChatInfo> callbackOnSuccess)
	{
		ChatGetMessagesTask task = new ChatGetMessagesTask(_chatSettings.ApiSettings.ApiChatMessages);
		task.SetParameterLatestLog(3);
		_chatConnectController.StartConnectCommon(task, delegate
		{
			ChatInfo chatInfo = task.ChatInfo;
			_chatConnectController.UpdatePollingInterval(chatInfo.WaitInterval);
			if (chatInfo.VisibleMessageList.Count > 0)
			{
				SaveReadLatestId(chatInfo.VisibleMessageList.Last().MessageId);
			}
			_pastVisibleMessageCnt += chatInfo.VisibleMessageList.Count;
			_chatLogUI.CreateChatLogView(chatInfo.MessageList, OnInitializeOldestLog, delegate
			{
				if (CheckNeedsPastVisibleMessage(chatInfo))
				{
					AddPastChatLog(delegate
					{
						_chatLogUI.ResetScrollDefaultPosition();
						callbackOnSuccess.Call(chatInfo);
					});
				}
				else
				{
					callbackOnSuccess.Call(chatInfo);
				}
			});
		});
	}

	private void OnInitializeOldestLog()
	{
		if (_isInitComplete)
		{
			AddPastChatLog();
		}
	}

	private bool CheckNeedsPastVisibleMessage(ChatInfo chatInfo)
	{
		if (_pastMessageRequestCnt > 30)
		{
			ResetPastMessageCnt();
			return false;
		}
		bool num = NeedsPastMessage(chatInfo);
		if (!num)
		{
			ResetPastMessageCnt();
		}
		return num;
	}

	private bool NeedsPastMessage(ChatInfo chatInfo)
	{
		if (_isPastLogComplete)
		{
			return false;
		}
		if (!chatInfo.IsIncludeInvisibleMessage)
		{
			return false;
		}
		if (_pastVisibleMessageCnt > 10)
		{
			return false;
		}
		return true;
	}

	private void ResetPastMessageCnt()
	{
		_pastVisibleMessageCnt = 0;
		_pastMessageRequestCnt = 0;
	}

	private void AddNewChatLog(Action callbackOnSuccess = null, bool isPolling = false)
	{
		ChatGetMessagesTask task = new ChatGetMessagesTask(_chatSettings.ApiSettings.ApiChatMessages);
		_chatConnectController.ResetPolling();
		if (_chatLogUI.ChatAllLogList.Count > 0)
		{
			int messageId = _chatLogUI.ChatAllLogList.Last().MessageId;
			task.SetParameter(messageId, eRequestDirection.NEW, _chatConnectController.PollingInterval);
		}
		else
		{
			task.SetParameterLatestLog(_chatConnectController.PollingInterval);
		}
		_chatConnectController.StartConnectCommon(task, delegate
		{
			ChatInfo chatInfo = task.ChatInfo;
			_chatConnectController.UpdatePollingInterval(chatInfo.WaitInterval);
			if (chatInfo.MessageList.Count <= 0)
			{
				callbackOnSuccess.Call();
			}
			else
			{
				if (chatInfo.VisibleMessageList.Count > 0)
				{
					SaveReadLatestId(chatInfo.VisibleMessageList.Last().MessageId);
				}
				_chatLogUI.AddChatLogView(chatInfo, eRequestDirection.NEW, GetCanUpdateUI(), callbackOnSuccess);
				OnAddNewChatMessage.Call(chatInfo);
			}
		}, isPolling);
	}

	private void AddPastChatLog(Action onFinish = null)
	{
		if (_isPastLogComplete)
		{
			ResetPastMessageCnt();
			onFinish.Call();
			return;
		}
		int messageId = _chatLogUI.ChatAllLogList[0].MessageId;
		ChatGetMessagesTask task = new ChatGetMessagesTask(_chatSettings.ApiSettings.ApiChatMessages);
		task.SetParameter(messageId, eRequestDirection.OLD, _chatConnectController.PollingInterval);
		_chatConnectController.StartConnectCommon(task, delegate
		{
			_pastMessageRequestCnt++;
			ChatInfo chatInfo = task.ChatInfo;
			if (chatInfo.MessageList.Count <= 0)
			{
				_isPastLogComplete = true;
			}
			_chatConnectController.UpdatePollingInterval(chatInfo.WaitInterval);
			_chatLogUI.AddChatLogView(chatInfo, eRequestDirection.OLD);
			_pastVisibleMessageCnt += chatInfo.VisibleMessageList.Count;
			if (CheckNeedsPastVisibleMessage(chatInfo))
			{
				AddPastChatLog(onFinish);
			}
			else
			{
				onFinish.Call();
			}
		});
	}

	private void SaveReadLatestId(int latestMessageId)
	{
		PlayerPrefsWrapper.SetValue(_chatSettings.PlayerPrefsKeyLatestReadChatMessageId, latestMessageId);
	}

	public void StartConnectCommon(NetworkTask task, Action<NetworkTask.ResultCode> callbackOnSuccess, bool isPolling = false)
	{
		_chatConnectController.StartConnectCommon(task, callbackOnSuccess, isPolling);
	}
}
