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

public class WorkshopJob : Job
{
	private static WorkshopJob workshop = null;

	public static WorkshopJob Instance {
		get {
			if (workshop == null)
				workshop = new WorkshopJob ();
			return workshop;
		}
	}

	private List<BaseRoom> assignedRooms = new List<BaseRoom> ();
	private GameController gameController;

	void Awake ()
	{
		var gameControllerGO = GameObject.FindGameObjectWithTag ("GameController");
		if (gameControllerGO != null)
			gameController = gameControllerGO.GetComponent<GameController> ();		
	}

	public override IEnumerator DoWork ()
	{
		StopJob = false;
		   
		while (!StopJob) {
			FixRoom ();
			yield return new WaitForSeconds (1f);
		}
		base.DoWork ();
	}

	public override BaseRoom GetWorkingRoom ()
	{
		var damagedRooms = gameController.GetDamagedRooms ().Where (x => !assignedRooms.Any (y => y.name == x.name));

		if (workRoom == null && damagedRooms != null) {
			workRoom = damagedRooms.FirstOrDefault ();
			assignedRooms.Add (workRoom);
		}
		return base.GetWorkRoom ();
	}

	private void FixRoom ()
	{
		if (workRoom.IsRoomDamaged ()) {
			workRoom.GiveHealth (Mathf.Clamp (10, 0, workRoom.MaxHealth));

			if (workRoom.RoomHealth () >= workRoom.MaxHealth) {
				assignedRooms.Remove (workRoom);
				workRoom = null;
				StopJob = true;
			}
		} else {
			workRoom = GetWorkingRoom ();
		}
	}
}
