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

public class AirplaneProcessor : MonoBehaviour {

    public Airplane plane = null;

    public readonly float SplooshRadius = 0.5f;
    public readonly float SplooshLength = 5.0f;

    public GameObject SplooshEffect = null;

    // Use this for initialization
    void Start()
    {

    }

    public bool AirplaneActive
    {
        get
        {
            return (Time.time + 3.0f) < plane.FinishTime;
        }
    }

    public void ReleasePlane(Vector3 start, Vector3 end)
    {
        plane.PayloadDropped = false;
        plane.StartTime = Time.time;
        plane.FinishTime = Time.time + 8.0f;

        plane.StartDropPoint = start;
        plane.EndDropPoint = end;

        Vector3 flightVector = (end - start).normalized;

        float outwarddistance = GetComponent<TreeFieldPopulator>().XVariance + GetComponent<TreeFieldPopulator>().ZVariance;

        Vector3 p0 = start - flightVector * outwarddistance;
        Vector3 p1 = start - flightVector * (outwarddistance / 3.0f);
        Vector3 p2 = start + flightVector * (outwarddistance / 3.0f);
        Vector3 p3 = start + flightVector * outwarddistance;

        plane.Path = new CubicBezierCurve(p0, p1, p2, p3);

        // Set the plane's rotation
        plane.transform.rotation = Quaternion.LookRotation(flightVector, Vector3.up);
    }

    void ReleasePayload()
    {
        Collider[] colliders = Physics.OverlapCapsule(plane.StartDropPoint, plane.EndDropPoint, SplooshRadius);

        foreach (Collider c in colliders)
        {
            Combustible combust = c.GetComponent<Combustible>();

            if (combust != null)
            {
                combust.SuppressedUntil = Time.time + 30.0f;
                GameObject.Instantiate(SplooshEffect, combust.transform.position, Quaternion.identity);
            }
        }
    }

    // Update is called once per frame
    void Update()
    {
        // Just process plane! It's the only plane in the game
        float t = (Time.time - plane.StartTime) / (plane.FinishTime - plane.StartTime);

        if (t < 1.0f)
        {
            plane.transform.position = plane.Path.CalculateCubicBezierPoint(t);
            if (!plane.PayloadDropped && t > 0.5f)
            {
                ReleasePayload();

                // Register that we dropped the payload
                plane.PayloadDropped = true;
            }
        }
    }
}
