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.Sound;
using Project.World;
using Project.Triggers;
using Project.Player;

namespace Project.Actors
{
    public class LordBehaviour : CoreBehaviour
    {
        private new MeshRenderer renderer;
        private bool starting = false;
        public float startDuration = 3f; 
        private UnityTimer startTimer;
        public GameObject dialog;
        public GameObject[] daemonsToActivate;
        public GameObject killMark;
        private bool battleBegun = false;

        public void Begin()
        {
            this.starting = true;
            Announce(new WorldLoader.UnloadAllAtRandomAction());
            Announce(new PlayerInput.FreezeInputAction());
        }

        // Use this for initialization
        protected override void InnerAwake()
        {
            AddGlobalActionHandler<PlayerInput.UnfreezeInputAction>(this, BeginBattle);
            this.renderer = this.transform.RecursivelyFindChild("Visual").GetComponent<MeshRenderer>();
            this.startTimer = new UnityTimer(this.startDuration, false);
           
        }

        protected override void InnerStart()
        {
            //for (int i = 0; i < this.daemonsToActivate.Length; i++)
            //{
            //    this.daemonsToActivate[i].SetActive(false);
            //}
        }

        // Update is called once per frame
        protected override void InnerUpdate()
        {
            if (this.starting)
            {
                //Announce(new WorldLoader.UnloadAllAtRandomAction());
                this.startTimer.Advance();
                this.renderer.material.color = new Color(1f, 1f, 1f, this.startTimer.GetCurrent() / this.startTimer.GetEnd());
                Time.timeScale = 1f;
                Time.fixedDeltaTime = 0.02f;
            }
            if (this.startTimer.IsComplete())
            {
                Interact(new DialogTrigger.StartDialogAction("LordSpeech"));
                this.startTimer.Reset();
                this.starting = false;
                //Instantiate(this.dialog, this.transform.position, new Quaternion());
            }

            if (this.battleBegun)
            {
                if (GameObject.FindObjectsOfType<BasicEnemySensor>().Length == 1)
                {
                    this.killMark.SetActive(true);
                    this.killMark.transform.RecursivelyFindChild("Visual").GetComponent<Loadable>().loaded = true;
                }
            }
        }

        private void BeginBattle(PlayerInput.UnfreezeInputAction action)
        {
            for (int i = 0; i < this.daemonsToActivate.Length; i++)
            {
                this.daemonsToActivate[i].SetActive(true);
            }
            this.battleBegun = true;
        }
    }
}