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

namespace GLogUnity
{
	public class GLogMonitor : MonoBehaviour
	{
		public float updateTime = 1.0f;
		private bool running = true;
		private float timePassed = 0;

		public delegate void HttpGetEvent(string url, string message);

		public HttpGetEvent HttpGetSuccess;
		public HttpGetEvent HttpGetFailed;

		public delegate void HttpPostEvent(string url, Dictionary<string, string> headers, byte[] content, string message);

		public HttpPostEvent HttpPostSuccess;
		public HttpPostEvent HttpPostFailed;

		private void Update()
		{
			if (running)
			{
				timePassed += Time.deltaTime;
				if (timePassed > updateTime)
				{
					timePassed -= updateTime;
					GLog.Update(updateTime);
				}
			}
		}

		//public void HttpPost(string url, Dictionary<string, string> headers, byte[] content)
		//{
		//	StartCoroutine(CoroutineHttpPost(url, headers, content));
		//}

		//private IEnumerator CoroutineHttpPost(string url, Dictionary<string, string> headers, byte[] content)
		//{
		//	//Upload
		//	WWW upload = new WWW(url, content, headers);
		//	yield return upload;

		//	//If an error occurs when uploading: store message in cache
		//	if (!string.IsNullOrEmpty(upload.error) && HttpPostFailed != null)
		//	{
		//		HttpPostFailed(url, headers, content, upload.error);
		//	}
		//	else if (HttpPostSuccess != null)
		//	{
		//		HttpPostSuccess(url, headers, content, upload.text);
		//	}
		//}

		public void DoGETRequest(string url, Action<string> successCallback, Action<string, bool, string, string> failureCallback)
		{
			UnityWebRequest request = UnityWebRequest.Get(url);
			StartCoroutine(DoRequest(request, null, successCallback, failureCallback ?? DefaultFailureCallback));
		}

		public void DoPOSTRequest(string url, string postData, Action<string> successCallback, Action<string, bool, string, string> failureCallback)
		{
			//UnityWebRequest request = UnityWebRequest.Post(url, postData);
			UnityWebRequest request =  new UnityWebRequest(url, "POST");
			byte[] bodyRaw = Encoding.UTF8.GetBytes(postData);
			request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
			request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
			request.SetRequestHeader("Content-Type", "application/json");
			StartCoroutine(DoRequest(request, postData, successCallback, failureCallback ?? DefaultFailureCallback));
		}

		IEnumerator DoRequest(UnityWebRequest request, string content, Action<string> successCallback, Action<string, bool, string, string> failureCallback)
		{
			yield return request.SendWebRequest();

			if (request.isNetworkError || request.isHttpError)
			{
				failureCallback.Invoke(request.error, request.isNetworkError, request.url, content);
			}
			else
			{
				successCallback?.Invoke(request.downloadHandler.text);
			}
		}

		void DefaultFailureCallback(string error, bool isNetworkError, string url, string content)
		{
			Debug.LogError($"Webrequest to {url} returned error: {error}");
		}

		private void OnApplicationQuit()
		{
			GLog.Shutdown();
		}

		private void OnApplicationPause(bool pause)
		{
			GLog.Event("GLog", "Application", "Pause", pause.ToString());
		}

		private void OnApplicationFocus(bool focus)
		{
			GLog.Event("GLog", "Application", "Focus", focus.ToString());
		}
	}
}
