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

using Nanolink;

namespace NanolinkDemo {

	public class MyPlayer : MonoBehaviour {
		int playerIndex = -1;

		float moveSpeed = 10f;
		const float DELTA = 0.5f;
		private float lastMove = 0;

		// Player 位置
		Vector3 targetPosition;

		// Use this for initialization
		void Start () {
			string subname = name.Substring (name.Length - 1);
			playerIndex = int.Parse (subname);

			targetPosition = transform.position;
		}
		
		// Update is called once per frame
		void Update () {
			// 回放模式下，不需要相应操作事件
			if(NanoClient.getInt ("mode") == 0)
				return;

			// 确保连接
			if(NanoClient.getString("status") != "connected")
				return;

			if(playerIndex != NanoClient.getInt("client-index")) {
				return;
			}

			// Player 移动
			doMove ();
		}

		void FixedUpdate() {
			transform.position = Vector3.LerpUnclamped (transform.position, targetPosition, Time.deltaTime * moveSpeed); // 10
		}

		// Player 移动
		void doMove() {
			bool bMoved = false;

			#region KeyboardEvents
			float deltaLR = 0;
			float deltaUD = 0;
			// 键盘操作，用于电脑上调试
			if (Input.GetKey (KeyCode.UpArrow)) {
				deltaUD = DELTA;
			} else if (Input.GetKey (KeyCode.RightArrow)) {
				deltaLR = DELTA;
			} else if (Input.GetKey (KeyCode.DownArrow)) {
				deltaUD = -DELTA;
			} else if (Input.GetKey (KeyCode.LeftArrow)) {
				deltaLR = -DELTA;
			}

			if(deltaLR != 0 || deltaUD != 0) {
				targetPosition = transform.position + new Vector3 (deltaLR, deltaUD, 0);
				bMoved = true;
			}
			#endregion

			#region TouchEvents
			if(Input.touchCount == 1) {
				Touch touch =Input.touches[0];
				if(touch.phase == TouchPhase.Moved) {
					Vector3 touchPosition = Camera.main.ScreenToWorldPoint (new Vector3 (touch.position.x, touch.position.y, 0));

					float diffTime = Time.realtimeSinceStartup - lastMove;
					float diffX = Mathf.Abs(touchPosition.x - targetPosition.x);
					float diffZ = Mathf.Abs(touchPosition.y - targetPosition.y);

					// 控制发送频率
					if(((diffX >= 0.25f || diffZ >= 0.25f) && diffTime >= 0.05f) || ((diffX > 0.1f || diffZ > 0.1) && diffTime > 0.1f)) {
						targetPosition = new Vector3 (touchPosition.x, touchPosition.y, transform.position.z);
						bMoved = true;
					}
				}
			}

			#endregion

			if (bMoved) {
				lastMove = Time.realtimeSinceStartup;
				moveEvent ();
			}
		}

		// 移动数据
		public void moveEvent() {
			Hashtable values = new Hashtable ();
			values.Add ("name", "move");
			values.Add ("target", targetPosition);

			MyClient.send (MySerialize.toBytes (values));
		}

		public void onEvent(Hashtable values) {
			string name = (string) values["name"];

			switch (name) {
			case "move":
				targetPosition = (Vector3)values ["target"];
				break;

			default:
				Debug.Log("未支持的 Player::onEvent 事件: " + name);
				break;
			}
		}
	}
}
