using UnityEngine;
using System.Collections;
using Framework.Entities;
using Framework.Extensions;
using System.Linq;
using System.Collections.Generic;
using Framework.InteractionSystem;
using Framework.Utility;
using Project.Actors;
using Project.Sound;
using Project.Effects;

namespace Project.Constructs
{
    public class FrequencyTrap : CoreBehaviour
    {
        public float offset = -1f;
        public float trapTime;
        public float holdTime;
        private UnityTimer trapTimer;
        private UnityTimer holdTimer;
        private bool on;
        private new BoxCollider collider;
        private new MeshRenderer renderer;

        // Use this for initialization
        protected override void InnerAwake()
        {
            if (this.offset == -1f)
            {
                this.offset = this.trapTime;
            }
            this.trapTimer = new UnityTimer(this.offset + 1f, false);
            this.holdTimer = new UnityTimer(this.holdTime, false);
            this.collider = GetComponent<BoxCollider>();
            this.renderer = this.transform.RecursivelyFindChild("Visual").GetComponent<MeshRenderer>();
            this.collider.enabled = false;
        }

        // Update is called once per frame
        protected override void InnerUpdate()
        {
            this.trapTimer.Advance();
            if(this.trapTimer.IsComplete())
            {
                if (!this.on)
                {
                    this.on = true;
                    TrapOn();
                }

                this.holdTimer.Advance();
                if(this.holdTimer.IsComplete())
                {
                    this.on = false;
                    TrapOff();
                    this.trapTimer.SetEnd(this.trapTime);
                    this.trapTimer.Reset();
                    this.holdTimer.Reset();
                }
            }
        }

        protected void OnTriggerEnter(Collider collider)
        {
            GameObject other = collider.gameObject;
            other.Interact(new Woundable.HurtAction(this, 1000f, this.transform.position));
        }

        private void TrapOn()
        {
            this.collider.enabled = true;
            GameObject steamBurstObject = (GameObject)Instantiate(Resources.Load("SteamBurst"), this.transform.position - (Vector3.up * 0.3f), Quaternion.LookRotation(Vector3.up));
            steamBurstObject.transform.parent = this.transform;
            steamBurstObject.GetComponent<SteamBurstEffect>().time = this.holdTime;
            //this.renderer.material.color = new Color(color.r, color.g, color.b, 1f);
        }

        private void TrapOff()
        {
            this.collider.enabled = false;   
        }
    }
}