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

public class Ship : MonoBehaviour
{
	public float launchCost = 150f;
	public float landCost = 50f;
	[SerializeField] public float speed = 10;
	[SerializeField] public float farThreshold = 100;
	[SerializeField] public float nearThreshold = 50;
	[SerializeField] public float goundedThreshold = 0;
	[SerializeField] public GameObject thrusters;

	private Coroutine coroutine;
	private float trueMaxHarvet;

	private void Start()
	{
		GameManager.Ship = this;
		trueMaxHarvet = GameManager.MaxHarvest - launchCost;
		LandShip();
	}

	private void Update()
	{
		if (coroutine == null && (GameManager.Harvest >= GameManager.MaxHarvest) && !GameManager.WeWin)
		{
			GameManager.PromptManager.Full();
		}
	}

	private void OnDestroy()
	{
		if (!GameManager.IsQuitting)
		{
			GameManager.Lose();
		}
	}

	public void LaunchShip()
	{
		if (coroutine == null)
		{
			if (GameManager.Harvest > launchCost + landCost)
			{
				coroutine = StartCoroutine(Launch());
			}
			else
			{
				GameManager.PromptManager.MoreGas();
			}
		}
	}

	public void LandShip()
	{
		if (coroutine == null)
		{
			coroutine = StartCoroutine(Land());
		}
	}

	private IEnumerator Land()
	{
		GameManager.PromptManager.Landing();
		bool near = false;
		GameManager.Interactable = false;
		GameManager.Sow(landCost);
		thrusters.SetActive(true);

		while (transform.position.y >= goundedThreshold)
		{
			yield return null;
			transform.position -= Vector3.up * speed * Time.deltaTime;

			if (!near & transform.position.y <= nearThreshold)
			{
				near = true;
				GameManager.LandingPad.Landing();
			}
		}

		if (transform.position.y <= 0)
		{
			transform.position = Vector3.zero;
		}

		thrusters.SetActive(false);
		GameManager.LandingPad.StopLanding();
		GameManager.Interactable = true;
		coroutine = null;
		GameManager.PromptManager.Landed();
	}
	
	private IEnumerator Launch()
	{
		GameManager.PromptManager.Launch();
		bool near = true;
		GameManager.Interactable = false;
		GameManager.Sow(launchCost);
		thrusters.SetActive(true);

		while (GameManager.LandingPad == null)
		{
			yield return null;
		}

		GameManager.LandingPad.Launching();

		while (transform.position.y <= farThreshold)
		{
			yield return null;
			transform.position += Vector3.up * speed * Time.deltaTime;

			if (near && transform.position.y >= nearThreshold)
			{
				near = false;
				GameManager.LandingPad.StopLaunching();
			}
		}

		thrusters.SetActive(false);

		if (GameManager.Harvest >= trueMaxHarvet || Mathf.Approximately(GameManager.Harvest, trueMaxHarvet))
		{
			GameManager.Interactable = true;
			GameManager.Win();
			coroutine = null;
		}
		else
		{
			coroutine = StartCoroutine(Land());
		}
	}
}
