//============================================================================
// Title:  Color Matching (Unity-Facebook)
//----------------------------------------------------------------------------
// File:   PHPHandler.cs
// Author: Nick Breslin (nickbreslin@gmail.com), Waddlefarm.org
//
// Copyright (c) Nick Breslin, 2009. All Rights Reserved.
//----------------------------------------------------------------------------
//
// * This license notice may not be removed or altered.
// * All project files are free for non-commercial or commercial use.
// * I appreciate personal notification if any part of this project is used.
// * All project files are provided "as is". I assume no responsibility for
//   results from using these files, nor should any support be expected.
// * Donations are appreciated, please visit: http://www.waddlefarm.org/donate
//
//============================================================================

using UnityEngine;
using System.Collections;

public class PHPHandler : MonoBehaviour
{
	public enum Action
	{
		Ping			= 0,
		GetUser			= 1,
		SubmitHighScore = 2
	}

	public enum Query
	{
		Sending,
		Success,
		Fail
	}

	public Director kDirector;
	public delegate void Callback( string data );
	public delegate void CallbackTexture( WWW data );
	public string sBaseCore			= "joju_mo_";
	public int sGameId				= 1;
	public string sBaseUrl			= "http://spartan.no-ip.org/mo/";
	public string sPingString		= "pong";
	
	[HideInInspector] public Query eQuery;
	
	void Awake()
	{
		if ( kDirector == null ) Debug.LogError( "kDirector == null" );
	}

	void Start()
	{
		StartCoroutine( Ping( true ) );
	}

	public void Request( Action eAction )
	{
		Request( eAction, null );
	}

	public void Request( WWWForm wForm, Action eAction )
	{
		Request( wForm, eAction, null );
	}
	
	public void Request( Action eAction, Callback callback )
	{
		Request( new WWWForm(), eAction, callback );
	}

	public void Request( WWWForm wForm, Action eAction, Callback callback )
	{
		wForm.AddField( "s", 1 );
		wForm.AddField( "game", sGameId );
		wForm.AddField( "exec", ( int )eAction );
		wForm.AddField( "hash", MakeHash() );

		StartCoroutine( Handle( new WWW( sBaseUrl, wForm ), callback ) );
	}

	public void RequestTexture( string url, CallbackTexture callback )
	{
		StartCoroutine( HandleTexture( new WWW( url ), callback ) );
	}

	public IEnumerator Handle( WWW www, Callback callback )
	{
		yield return www;

		if ( www.error == null )
		{
			if ( callback != null )
				callback( www.data );
		}
		else
		{

		}

		www.Dispose();
	}

	public IEnumerator HandleTexture( WWW www, CallbackTexture callback )
	{
		yield return www;

    	if( callback != null )
			callback( www );
		
		www.Dispose();
	}
	
	IEnumerator Ping( bool bIsStart )
	{
		Log.Add( "Pinging Server..." );

		eQuery = PHPHandler.Query.Sending;		
		Request( PHPHandler.Action.Ping, PingResult );

		while ( eQuery == PHPHandler.Query.Sending )
		{
			yield return new WaitForSeconds( 0 );
		}
		
		string sConnection = "Connection ";
		Log.Type eType = Log.Type.Message;
		
		if( eQuery == PHPHandler.Query.Fail )
		{
			sConnection += "Failed.";
			eType = Log.Type.Error;
		}
		else if ( eQuery == PHPHandler.Query.Success )
		{
			sConnection += "Established.";
		}

		Log.Add( sConnection, eType );
		
		yield return new WaitForSeconds( 0 );

		if ( eQuery == PHPHandler.Query.Success && bIsStart )
		{
			kDirector.kUserManager.GetUserData();
		}
	}

	public void PingResult( string data )
	{
		Debug.Log( data + " == " + sPingString );

		if ( data == sPingString )
		{
			eQuery = Query.Success;
		}
		else
		{
			eQuery = Query.Fail;
		}
	}

	public string MakeHash()
	{
		return MakeHash( "" );
	}

	public string MakeHash( string value )
	{
		if ( kDirector.kUserManager.kUser != null )
		{
			return Md5Sum( sBaseCore + kDirector.kUserManager.kUser.fbid + "_" + sGameId + "_" + value );
		}

		return Md5Sum( sBaseCore + "_" + sGameId + "_" + value );
	}

	public string Md5Sum( string strToEncrypt )
	{
	    System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
	    byte[] bytes = ue.GetBytes(strToEncrypt);

	    System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
	    byte[] hashBytes = md5.ComputeHash( bytes );

	    string hashString = "";

		for ( int i = 0; i < hashBytes.Length; i++ )
		{
			hashString += System.Convert.ToString( hashBytes[i], 16 ).PadLeft( 2, '0' );
		}

	    return hashString.PadLeft( 32, '0' );
	}
}