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

using UnityEngine.SceneManagement;

namespace NanolinkDemo {

	public class MyNetwork : MonoBehaviour {
		// 对战类型，1对1 或者 多人对战
		static public int mode = 2;

		// 等级匹配
		static public uint level = 1;
		// 房间号，局域网
		static public string group = "";

		MyClient myClient;

		// Use this for initialization
		void Start () {
			myClient = new MyClient();

			MyClient.init ("51ddbe52ab2ff1b4", mode);

			if(mode == 0) {
				load ();

				return;
			}

			// 开启存档与回放功能
			MyClient.config ("time-machine", "true");

			// 游戏上线时，注释掉 debug-level 调试信息
			// MyClient.config ("debug-level", "7");

			// 获取匹配方式
			if (group == "") {
				MyClient.connect (level);
			} else {
				if (group == "lan")
					MyClient.connect ("");
				else
					MyClient.connect (group);
			}
		}

		void FixedUpdate () {
			if(myClient != null)
				myClient.doUpdate ();
		}

		void OnGUI () {
			if(myClient != null)
				myClient.drawGUI ();
		}

		// =============

		public void onButtonClick(string name) {
			if(name == "")
				return;
		
			switch (name) {
			// 返回主界面
			case "main":
				MyClient.disconnect ();

				SceneManager.LoadScene ("Main");
				break;

			case "replay":
				// 断开当前连接
				MyClient.disconnect ();

				// 存档
				save ();

				// 回放模式
				mode = 0;

				// 重新加载当前场景
				SceneManager.LoadScene (SceneManager.GetActiveScene().buildIndex);
				break;

			}
		}

		// 存档
		// 通常用于游戏结束时，玩家选择保存当局存档，存档文件很小方便给好友分享
		private void save() {
			if (MyClient.getInt ("mode") == 0)
				return;
			
			string archivesFilePath = "";
			string archivesFileName = "archives_file.dat";
#if UNITY_EDITOR
			archivesFilePath = Application.dataPath;
#else
			archivesFilePath = Application.persistentDataPath;
#endif

			MyClient.save (archivesFilePath + "/" + archivesFileName);
		}

		// 回放
		// 支持快速，慢速回放
		private void load() {
			if (MyClient.getInt ("mode") != 0)
				return;
			
			string archivesFilePath = "";
			string archivesFileName = "archives_file.dat";
#if UNITY_EDITOR
			archivesFilePath = Application.dataPath;
#else
			archivesFilePath = Application.persistentDataPath;
#endif

			MyClient.load (archivesFilePath + "/" + archivesFileName);
		}
	}
}
