using UnityEngine;
using System.Collections.Generic;

public class Render {

    protected float renderDuration;
    protected float nextRenderDelay=-1;
    private float startTime;
    float progress=0;
    private bool done;

    public int ForTurn = -1;
    public float Duration { get { return renderDuration;  } }
    public float NextRenderDelay { get { return (1-progress) * ((nextRenderDelay == -1) ? renderDuration : nextRenderDelay); } }

    private List<RenderTrigger> triggers = new List<RenderTrigger>();

    public void AddTrigger(RenderTrigger trigger)
    {
        triggers.Add(trigger);
    }

    public void StartRender()
    {
        done = false;
        startTime = Time.time;
        Initialize();
    }

    public void UpdateRender()
    {
        if (renderDuration != 0)
        {
            float timeUsed = Time.time - startTime;
            progress = Mathf.Clamp(timeUsed / renderDuration, 0, 1);
        }
        else
            progress = 1;

        try
        {
            RenderProgress(progress);
            CheckTriggers(progress);
        }
        catch (System.Exception e)
        {
            Debug.LogError("Exception thrown by Render " + this + ": \n" + e.ToString());
        }

        if (progress == 1)
            done = true;
    }

    public void SkipToEnd()
    {
        renderDuration = 0;
        UpdateRender();
    }

    public virtual void Initialize() { }

    public virtual void RenderProgress(float progressFactor) { }

    public virtual bool IsDone()
    {
        return done;
    }

    public void CheckTriggers(float progress)
    {
        foreach (RenderTrigger trigger in triggers)
            trigger.CheckDrop(progress);
    }

}
