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

namespace InteractiveModules
{
    public class NastyPizza : InteractiveModule
    {
        [SerializeField] private GameScreenAsset nextScreen;

        [SerializeField] private float RandomRadius;

        PizzaBug[] bugs;
        Transform pizzaGroup;
        private int activePieces;

        public override void Activate(ScreenController screenController)
        {
            base.Activate(screenController);
            screenController.SetBackgroundColor(ColorType.White);
        }

        // Start is called before the first frame update
        void Start()
        {
            bugs = transform.Find("BugGroup").GetComponentsInChildren<PizzaBug>();
            pizzaGroup = transform.Find("PieceGroup");
            activePieces = pizzaGroup.childCount;
        }

        // Update is called once per frame
        void Update()
        {

        }

        public void GlobalClick()
        {
            Debug.Log("Global click");
            if (activePieces < 1)
            {
                currentScreenController.LoadScreen(nextScreen);
            }
        }

        public void PizzaClicked(GameObject pizzaPiece)
        {
            if (pizzaPiece.activeSelf)
            {
                GameObject freePizzaPiece = null;
                GetComponent<AudioSource>().Play();
                pizzaPiece.SetActive(false);
                activePieces--;

                if (activePieces != 0)
                {
                    int r = (int)(Random.value * pizzaGroup.childCount);
                    for (int i = 0; i < pizzaGroup.childCount; ++i)
                    {
                        int index = (i + r) % pizzaGroup.childCount;
                        if (pizzaGroup.GetChild(index).gameObject.activeSelf)
                        {
                            freePizzaPiece = pizzaGroup.GetChild(index).gameObject;
                            break;
                        }
                    }
                }
                else
                {
                    GetComponent<BoxCollider2D>().enabled = true;
                }
                
                foreach (PizzaBug bug in bugs)
                {
                    bug.MoveToPizzaPiece(freePizzaPiece, RandomRadius);
                }
            }
        }
    }
}
