using System;
using System.Text;
using Cute;
using UnityEngine;
using UnityEngine.Networking;

namespace Wizard;

public class GenerateDeckImageTask : BaseTask
{
	public class GenerateDeckCodeTaskParam : BaseParam
	{
		public int clan;

		public int deck_format;

		public int[] cardID;

		public int[] phantomCardID;

		public string rotation_id;
	}

	public class GenerateDeckCodeTaskUseSubClassParam : BaseParam
	{
		public int clan;

		public int sub_clan;

		public int deck_format;

		public int[] cardID;

		public int[] phantomCardID;
	}

	private const string HEADER_TWITTER_KEY = "X-TWITTER-MESSAGE";

	public override string Url
	{
		get
		{
			string arg = Data.SystemText.Get("System_0045");
			string arg2 = string.Format(ApiType.ApiList[base.type], arg);
			return $"{CustomPreference.GetDeckBuilderServerURL()}{arg2}";
		}
	}

	public byte[] ImageBytes { get; private set; }

	public string TwitterMessage { get; private set; }

	public GenerateDeckImageTask()
	{
		base.type = ApiType.Type.GenerateDeckImage;
		base.CallbackOnUnityWebRequestDone = HandleResponseData;
	}

	public void SetParameter(int clan_id, GenerateDeckCodeTask.SubmitDeckType type, int[] card_id_array, string rotationId, int[] phantomCardIdList = null)
	{
		GenerateDeckCodeTaskParam generateDeckCodeTaskParam = new GenerateDeckCodeTaskParam();
		generateDeckCodeTaskParam.clan = clan_id;
		generateDeckCodeTaskParam.deck_format = (int)type;
		generateDeckCodeTaskParam.cardID = card_id_array;
		generateDeckCodeTaskParam.phantomCardID = phantomCardIdList;
		generateDeckCodeTaskParam.rotation_id = rotationId;
		base.Params = generateDeckCodeTaskParam;
	}

	public void SetParameter(int mainClassId, int subClassId, GenerateDeckCodeTask.SubmitDeckType type, int[] card_id_array, int[] phantomCardIdList = null)
	{
		GenerateDeckCodeTaskUseSubClassParam generateDeckCodeTaskUseSubClassParam = new GenerateDeckCodeTaskUseSubClassParam();
		generateDeckCodeTaskUseSubClassParam.clan = mainClassId;
		generateDeckCodeTaskUseSubClassParam.sub_clan = subClassId;
		generateDeckCodeTaskUseSubClassParam.deck_format = (int)type;
		generateDeckCodeTaskUseSubClassParam.cardID = card_id_array;
		generateDeckCodeTaskUseSubClassParam.phantomCardID = phantomCardIdList;
		base.Params = generateDeckCodeTaskUseSubClassParam;
	}

	private void HandleResponseData(UnityWebRequest www)
	{
		if (www.GetResponseHeaders().TryGetValue("X-TWITTER-MESSAGE", out var value))
		{
			byte[] bytes = Convert.FromBase64String(value);
			TwitterMessage = Encoding.UTF8.GetString(bytes);
		}
		SaveImageToBytes(www);
		if (base.CallbackOnSuccess != null)
		{
			base.CallbackOnSuccess(ResultCode.Success);
		}
	}

	private void SaveImageToBytes(UnityWebRequest www)
	{
		Texture2D texture2D = new Texture2D(1, 1);
		texture2D.LoadImage(www.downloadHandler.data);
		ImageBytes = texture2D.EncodeToPNG();
		UnityEngine.Object.Destroy(texture2D);
	}
}
