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

public class JailerRouteManager : SingletonMonoBehaviour<JailerRouteManager> {
	public float roomcollider_scale = 2.0f;

	private List<RouteMarker> markerlist = new List<RouteMarker>();
	private List<Room> roomlist = new List<Room> ();
	private List<RouteMarker> route = new List<RouteMarker> ();
	private bool isroom = false;
	private Room checkroom = null;
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}

	// マーカーを登録
	public void addMarker(RouteMarker marker){
		markerlist.Add (marker);
	}

	// 部屋を登録
	public void addRoom(Room room){
		roomlist.Add (room);
	}

	public RouteMarker getNearMarker(Vector3 position){
		float min_dist = Mathf.Infinity;
		int min_num = -1;
		for (int i = 0; i < markerlist.Count; i++) {
			float dist = Vector3.Distance (markerlist [i].transform.position, position);
			if (dist < min_dist) {
				min_dist = dist;
				min_num = i;
			}
		}
		return markerlist [min_num];
	}

	public void setRouteEdge(RouteMarker start,RouteMarker goal,Vector3 position){
		// 初期化
		for (int i = 0; i < markerlist.Count; i++) {
			markerlist [i].resetSearch ();
		}
		// ダイクストラ　最短距離探索
		List<RouteMarker> dijklist = new List<RouteMarker> ();
		dijklist.Add (goal);
		goal.setSeachDistance(0);
		while (dijklist.Count > 0) {
			RouteMarker marker_me = dijklist [0];
			for (int i = 0; i < marker_me.markerlist_connect.Length; i++) {
				RouteMarker marker_target = marker_me.markerlist_connect [i];
				float dist_total = marker_me.getSearchDistance() + Vector3.Distance (marker_me.transform.position, marker_target.transform.position);
				if (marker_target.getSearchDistance () > dist_total) {
					marker_target.setSearchNext(marker_me);
					marker_target.setSeachDistance(dist_total);
					if (marker_target != start) {
						dijklist.Add (marker_target);
					}
				}
			}
			dijklist.RemoveAt (0);
		}
		// ルート決定
		RouteMarker nowrm = start;
		route.Clear ();
		while (true) {
			route.Add (nowrm);
			nowrm = nowrm.getSearchNext ();
			if (nowrm == null) {
				break;
			}
		}

		// ルームチェック
		if (route.Count <= 1) {
			float min_dist = Mathf.Infinity;
			int min_num = -1;
			for (int i = 0; i < roomlist.Count; i++) {
				float dist = Vector3.Distance (position, roomlist [i].transform.position);
				if (dist < min_dist) {
					min_dist = dist;
					min_num = i;
				}
			}
			if (min_dist <= roomcollider_scale) {
				isroom = true;
				checkroom = roomlist [min_num];
			}
		}
	}

	public RouteMarker getNextMarker(){
		if (route.Count > 0) {
			return route [0];
		}
		return null;
	}
	public void goNextMarker(){
		route.RemoveAt (0);
	}

	public bool isCheckRoom(){
		return isroom;
	}
	public Room getCheckRoom(){
		return checkroom;
	}
	public void resetRoomCheck(){
		isroom = false;
		checkroom = null;
	}
}
