using System;
using System.Collections;
using System.Collections.Generic;
using Cute;
using UnityEngine;
using Wizard.Story;

namespace Wizard;

public class StorySelectPage : UIBase
{
	private const int NO_SECTION_ID = -1;

	private const int PROLOGUE_SECTION_ID = 0;

	private const int MAX_NUM_BTN_IN_TABLE = 6;

	private const float DRAG_DEGREE = 70f;

	private const float MOVE_PAGE_DURATION = 0.2f;

	[SerializeField]
	private GameObject _backGroundObj;

	[SerializeField]
	private UIAnchor _backGroundEffectAnchor;

	[SerializeField]
	private UIGrid _sectionTableParent;

	[SerializeField]
	private UIGrid _originalSectionTable;

	[SerializeField]
	private StorySectionBtn _originalSectionBtn;

	[SerializeField]
	private BoxCollider _flickCollider;

	[SerializeField]
	private BoxCollider _leftButton;

	[SerializeField]
	private BoxCollider _rightButton;

	[SerializeField]
	private UIPageIndicator _indicator;

	[SerializeField]
	private GameObject _mainStoryBgRoot;

	[SerializeField]
	private GameObject _limitedStoryBgRoot;

	[SerializeField]
	private UITexture _limitedStoryBgTexture;

	[SerializeField]
	private GameObject _bgEffectRoot;

	private string _limitedStoryBgTextureName = "bg_limited_story";

	private string _limitedStoryBgEffectName = "cmn_bg_limited_story_1";

	private readonly Vector3 EFFECT_SCALE = new Vector3(320f, 320f, 320f);

	private List<UIGrid> _sectionTableList = new List<UIGrid>();

	private List<StorySectionBtn> _sectionBtnList = new List<StorySectionBtn>();

	private List<string> _loadPathList = new List<string>();

	private TopBar _topBar;

	private Vector3 _parentFirstPos;

	private int _currentPage;

	private bool _isChangePage;

	private string _lastChapterClearTextId;

	public static int SelectSectionId = -1;

	private SelectedStoryInfo SelectedStoryInfo => Data.SelectedStoryInfo;

	private UIManager.ViewScene ChapterSelectionView => SelectedStoryInfo.ChapterSelectionView;

	private bool IsEntranceLimitedStory => SelectedStoryInfo.StoryEntranceType == StoryEntranceType.LimitedStory;

	public override void onFirstStart()
	{
		_backGroundObj.SetLayer(LayerMask.NameToLayer("FrontUI"), isSetChildren: true);
		_backGroundEffectAnchor.uiCamera = NGUITools.FindCameraForLayer(_backGroundEffectAnchor.gameObject.layer);
		base.IsShowFooterMenu = true;
		base.onFirstStart();
	}

	protected override void onOpen()
	{
		base.onOpen();
		ResetSelectedStoryInfo();
		_mainStoryBgRoot.SetActive(!IsEntranceLimitedStory);
		_limitedStoryBgRoot.SetActive(IsEntranceLimitedStory);
		StorySectionTask storySectionTask = new StorySectionTask(SelectedStoryInfo);
		storySectionTask.SetParameter(isDispFirstTips: false);
		StartCoroutine(Toolbox.NetworkManager.Connect(storySectionTask, delegate
		{
			InitOrRedirect();
		}));
	}

	protected override void onClose()
	{
		Final();
		base.onClose();
	}

	private void InitOrRedirect()
	{
		StorySectionData storySectionData = null;
		if (SelectSectionId != -1)
		{
			storySectionData = Data.StoryWorldDataManager.FindSectionData(SelectSectionId);
			SelectSectionId = -1;
		}
		if (storySectionData != null)
		{
			ChangeViewBySectionData(storySectionData, isRedirect: true);
		}
		else
		{
			Init();
		}
		UIManager.GetInstance()._Footer.TurnOffStoryBadgeIcon(isTurnOffDisplayBadgeFlag: true);
	}

	private void Init()
	{
		InitTopBar();
		InitFooter();
		InitStorySelect();
	}

	private void Final()
	{
		Toolbox.ResourcesManager.RemoveAssetGroup(_loadPathList);
		_loadPathList.Clear();
	}

	private void InitTopBar()
	{
		UIManager.ChangeViewSceneParam changeViewSceneParam = new UIManager.ChangeViewSceneParam();
		changeViewSceneParam.MyPageMenuIndex = 1;
		changeViewSceneParam.IsCutCardMotion = true;
		_topBar = UIManager.GetInstance().CreateTopBar(base.gameObject, Data.SystemText.Get("Story_0059"), UIManager.ViewScene.MyPage, MoneyDraw: false, changeViewSceneParam);
		_topBar.gameObject.layer = LayerMask.NameToLayer("MyPage");
	}

	private void InitFooter()
	{
		UIManager instance = UIManager.GetInstance();
		instance.setBackScene(base.gameObject, UIManager.ViewScene.MyPage);
		instance._Footer.UpdateCurrentIndex(1);
	}

	private void InitStorySelect()
	{
		_parentFirstPos = _sectionTableParent.transform.localPosition;
		UIEventListener uIEventListener = UIEventListener.Get(_flickCollider.gameObject);
		uIEventListener.onDrag = (UIEventListener.VectorDelegate)Delegate.Combine(uIEventListener.onDrag, new UIEventListener.VectorDelegate(OnDragPanel));
		UIEventListener uIEventListener2 = UIEventListener.Get(_rightButton.gameObject);
		uIEventListener2.onClick = (UIEventListener.VoidDelegate)Delegate.Combine(uIEventListener2.onClick, (UIEventListener.VoidDelegate)delegate
		{
			NextPage();
		});
		UIEventListener uIEventListener3 = UIEventListener.Get(_leftButton.gameObject);
		uIEventListener3.onClick = (UIEventListener.VoidDelegate)Delegate.Combine(uIEventListener3.onClick, (UIEventListener.VoidDelegate)delegate
		{
			PrevPage();
		});
		StartCoroutine(LoadImages(delegate
		{
			SetSectionBtn();
			_indicator.Init(_sectionTableList.Count);
			ChangePage(1);
			UIManager.GetInstance().OnReadyViewScene(isFadein: true, null, OnFinishFadeIn);
		}));
	}

	private void OnDragPanel(GameObject obj, Vector2 dir)
	{
		if (dir.x >= 70f)
		{
			PrevPage();
		}
		else if (dir.x <= -70f)
		{
			NextPage();
		}
	}

	private void NextPage()
	{
		if (ChangePage(_currentPage + 1))
		{
			GameMgr.GetIns().GetSoundMgr().PlaySe(Se.TYPE.SYS_SLIDE_BTN);
		}
	}

	private void PrevPage()
	{
		if (ChangePage(_currentPage - 1))
		{
			GameMgr.GetIns().GetSoundMgr().PlaySe(Se.TYPE.SYS_SLIDE_BTN);
		}
	}

	private bool ChangePage(int page, bool isAnimation = true)
	{
		if (_isChangePage)
		{
			return false;
		}
		if (!IsValidPage(page))
		{
			return false;
		}
		_currentPage = page;
		Vector3 vector = _parentFirstPos + Vector3.left * _sectionTableParent.cellWidth * (page - 1);
		if (isAnimation)
		{
			TweenPosition tweenPosition = TweenPosition.Begin(_sectionTableParent.gameObject, 0.2f, vector);
			_isChangePage = true;
			tweenPosition.SetOnFinished(delegate
			{
				_isChangePage = false;
			});
		}
		else
		{
			_sectionTableParent.transform.localPosition = vector;
			_isChangePage = false;
		}
		_rightButton.gameObject.SetActive(IsValidPage(page + 1));
		_leftButton.gameObject.SetActive(IsValidPage(page - 1));
		_indicator.UpdateIndicator(page);
		return true;
	}

	private bool IsValidPage(int page)
	{
		if (_sectionTableList.Count > 0 && page > 0)
		{
			return page <= _sectionTableList.Count;
		}
		return false;
	}

	private void ChangeViewBySectionData(StorySectionData inSectionData, bool isRedirect = false)
	{
		if (inSectionData.Id == 0)
		{
			OnClickTutorialSectionBtn();
			return;
		}
		SelectedStoryInfo.SetSection(inSectionData);
		GameMgr.GetIns().GetDataMgr().m_BattleType = DataMgr.BattleType.Story;
		UIManager.ChangeViewSceneParam changeViewSceneParam = new UIManager.ChangeViewSceneParam();
		if (isRedirect)
		{
			changeViewSceneParam.WaitTime = 0f;
		}
		if (inSectionData.IsLeaderSelect)
		{
			UIManager.GetInstance().ChangeViewScene(UIManager.ViewScene.ClassSelectionPage, changeViewSceneParam, ClassSelectionPageParam.CreateStorySelect());
		}
		else
		{
			UIManager.GetInstance().ChangeViewScene(ChapterSelectionView, changeViewSceneParam);
		}
	}

	private void OnClickTutorialSectionBtn()
	{
		SelectedStoryInfo.SetSection(StorySection.TUTORIAL_SECTION_ID);
		SelectedStoryInfo.SetSectionChara(500008);
		UIManager.GetInstance().ChangeViewScene(UIManager.ViewScene.AreaSelect);
	}

	private IEnumerator LoadImages(Action callBack)
	{
		IReadOnlyList<StorySectionData> sectionDatas = Data.StoryWorldDataManager.SectionDatas;
		ResourcesManager resMgr = Toolbox.ResourcesManager;
		List<string> assetList = new List<string>();
		for (int i = 0; i < sectionDatas.Count; i++)
		{
			string imageName = sectionDatas[i].ImageName;
			assetList.Add(resMgr.GetAssetTypePath($"{imageName}_off", ResourcesManager.AssetLoadPathType.UiStory));
			assetList.Add(resMgr.GetAssetTypePath($"{imageName}_on", ResourcesManager.AssetLoadPathType.UiStory));
		}
		if (IsEntranceLimitedStory)
		{
			assetList.Add(resMgr.GetAssetTypePath(_limitedStoryBgTextureName, ResourcesManager.AssetLoadPathType.UiStory));
			assetList.Add(resMgr.GetAssetTypePath(_limitedStoryBgEffectName, ResourcesManager.AssetLoadPathType.Effect2D));
		}
		yield return StartCoroutine(resMgr.LoadAssetGroupAsync(assetList, null));
		_loadPathList.AddRange(assetList);
		if (IsEntranceLimitedStory)
		{
			bool isLoadBGEffect = false;
			GameObject effectObject = UnityEngine.Object.Instantiate(resMgr.LoadObject<GameObject>(resMgr.GetAssetTypePath(_limitedStoryBgEffectName, ResourcesManager.AssetLoadPathType.Effect2D, isfetch: true)));
			effectObject.transform.SetParent(_bgEffectRoot.transform);
			effectObject.transform.localScale = EFFECT_SCALE;
			_limitedStoryBgTexture.mainTexture = resMgr.LoadObject(resMgr.GetAssetTypePath(_limitedStoryBgTextureName, ResourcesManager.AssetLoadPathType.UiStory, isfetch: true)) as Texture;
			_loadPathList.AddRange(GameMgr.GetIns().GetEffectMgr().SetUIParticleShader(effectObject, delegate
			{
				isLoadBGEffect = true;
			}));
			while (!isLoadBGEffect)
			{
				yield return null;
			}
			effectObject.SetActive(value: true);
		}
		callBack.Call();
	}

	private void SetSectionBtn()
	{
		IReadOnlyList<StorySectionData> sectionDatas = Data.StoryWorldDataManager.SectionDatas;
		_sectionBtnList.Clear();
		for (int i = 0; i < sectionDatas.Count; i++)
		{
			StorySectionData data = sectionDatas[i];
			CreateSectionBtn(onClickSectionBtn: (!data.IsSpoiler) ? ((Action)delegate
			{
				ChangeViewBySectionData(data);
			}) : ((Action)delegate
			{
				CreateSpoilerConfirmationDialog(data);
			}), sectionData: data);
		}
		_originalSectionBtn.gameObject.SetActive(value: false);
		for (int num = 0; num < _sectionTableList.Count; num++)
		{
			_sectionTableList[num].Reposition();
		}
		_sectionTableParent.Reposition();
	}

	public void CreateSpoilerConfirmationDialog(StorySectionData inSectionData)
	{
		SystemText systemText = Data.SystemText;
		DialogBase dialogBase = UIManager.GetInstance().CreateDialogClose();
		dialogBase.SetButtonLayout(DialogBase.ButtonLayout.BlueBtn_CancelBtn);
		dialogBase.SetTitleLabel(systemText.Get("Story_0080"));
		dialogBase.SetButtonText(systemText.Get("Story_0081"));
		string text = inSectionData.Name;
		text = text.Replace("\n", " ");
		string text2 = systemText.Get("Story_0076", text, Data.Master.GetStorySectionTitleText(inSectionData.SpoilerMessage));
		dialogBase.SetText(text2);
		dialogBase.onPushButton1 = delegate
		{
			ChangeViewBySectionData(inSectionData);
		};
	}

	private void CreateSectionBtn(StorySectionData sectionData, Action onClickSectionBtn)
	{
		if (_sectionBtnList.Count % 6 == 0)
		{
			_sectionTableList.Add(NGUITools.AddChild(_sectionTableParent.gameObject, _originalSectionTable.gameObject).GetComponent<UIGrid>());
		}
		GameObject obj = NGUITools.AddChild(_sectionTableList[_sectionTableList.Count - 1].gameObject, _originalSectionBtn.gameObject);
		StorySectionBtn component = obj.GetComponent<StorySectionBtn>();
		bool isLimitedOrEventStory = sectionData.StoryApiType == StoryApiType.LimitedStory || sectionData.StoryApiType == StoryApiType.EventStory;
		component.SetData(sectionData, onClickSectionBtn, isLimitedOrEventStory);
		component.DispNewMark(sectionData.IsNew);
		_sectionBtnList.Add(component);
		UIEventListener uIEventListener = UIEventListener.Get(obj.gameObject);
		uIEventListener.onDrag = (UIEventListener.VectorDelegate)Delegate.Combine(uIEventListener.onDrag, new UIEventListener.VectorDelegate(OnDragPanel));
	}

	private void OnFinishFadeIn()
	{
		if (_lastChapterClearTextId != null)
		{
			SystemText systemText = Data.SystemText;
			DialogBase dialogBase = UIManager.GetInstance().CreateDialogClose();
			dialogBase.SetButtonLayout(DialogBase.ButtonLayout.OkBtn);
			dialogBase.SetTitleLabel(systemText.Get("Common_0021"));
			dialogBase.SetButtonText(systemText.Get("Common_0004"));
			dialogBase.SetText(systemText.Get(_lastChapterClearTextId));
			dialogBase.OnClose = delegate
			{
				AreaSelectUI.CheckPreBuildDeckConfirmDialog();
			};
			_lastChapterClearTextId = null;
		}
	}

	private void ResetSelectedStoryInfo()
	{
		_lastChapterClearTextId = SelectedStoryInfo.LastChapterClearTextId;
		SelectedStoryInfo.ClearInfoForSectionSelectionScene();
	}
}
