﻿using UnityEngine;
using System.Collections;

public class PortalMainViewingCameraBehaviour : MonoBehaviour {

    static readonly float teleportCooldownSeconds = 1;

    public delegate void EventHandler();

    public Vector3 PortalCameraMidEyesPosition;
    public Vector3 FutureOffset;
    public Quaternion FutureRotation;
    public EventHandler TeleportationCallbacks;

    public IEnumerator Teleport(EventHandler beforeCallback, EventHandler afterCallback) {
        beforeCallback();
        TeleportationCallbacks += afterCallback;

        yield return new WaitForEndOfFrame();

        Globals.HMDOrigin.Translate(FutureOffset, Space.World);
        Globals.HMDOrigin.RotateAround(PortalCameraMidEyesPosition, Vector3.up, FutureRotation.eulerAngles[1]);

        Invoke("AfterTeleportation", teleportCooldownSeconds);
    }

    void AfterTeleportation() {
        InvokeOnce(TeleportationCallbacks);
    }

    void Invoke(EventHandler eventHandler) {
        if (eventHandler != null) {
            eventHandler();
        }
    }

    void InvokeOnce(EventHandler eventHandler) {
        Invoke(eventHandler);
        RemoveAll(eventHandler);
    }

    void RemoveAll(EventHandler eventHandler) {
        if (eventHandler != null) {
            foreach (var @delegate in eventHandler.GetInvocationList()) {
                eventHandler -= (EventHandler)@delegate;
            }
        }
    }
}
