using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;

namespace I2.Loc
{
	public class TranslationJob_GET : TranslationJob_WWW
	{
		public TranslationJob_GET(Dictionary<string, TranslationQuery> requests, Action<Dictionary<string, TranslationQuery>, string> OnTranslationReady)
		{
			this._requests = requests;
			this._OnTranslationReady = OnTranslationReady;
			this.mQueries = GoogleTranslation.ConvertTranslationRequest(requests, true);
			this.GetState();
		}

		private void ExecuteNextQuery()
		{
			if (this.mQueries.Count == 0)
			{
				this.mJobState = TranslationJob.eJobState.Succeeded;
				return;
			}
			int index = this.mQueries.Count - 1;
			string arg = this.mQueries[index];
			this.mQueries.RemoveAt(index);
			string url = string.Format("{0}?action=Translate&list={1}", LocalizationManager.GetWebServiceURL(null), arg);
			this.www = new WWW(url);
		}

		public override TranslationJob.eJobState GetState()
		{
			if (this.www != null && this.www.isDone)
			{
				this.ProcessResult(this.www.bytes, this.www.error);
				this.www.Dispose();
				this.www = null;
			}
			if (this.www == null)
			{
				this.ExecuteNextQuery();
			}
			return this.mJobState;
		}

		public void ProcessResult(byte[] bytes, string errorMsg)
		{
			if (string.IsNullOrEmpty(errorMsg))
			{
				string @string = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
				errorMsg = GoogleTranslation.ParseTranslationResult(@string, this._requests);
				if (string.IsNullOrEmpty(errorMsg))
				{
					if (this._OnTranslationReady != null)
					{
						this._OnTranslationReady(this._requests, null);
					}
					return;
				}
			}
			this.mJobState = TranslationJob.eJobState.Failed;
			this.mErrorMessage = errorMsg;
		}

		private Dictionary<string, TranslationQuery> _requests;

		private Action<Dictionary<string, TranslationQuery>, string> _OnTranslationReady;

		private List<string> mQueries;

		public string mErrorMessage;
	}
}
