using UnityEngine;
using System.Collections;

public class SummonArea : MonoBehaviour
{
    public GameObject[] MarkerPrefabs;
    public float RadiusX;
    public float RadiusY;
    public float MinMarkerScale;
    public float MaxMarkerScale;

    private SummonMarker[] _markers;

    private GameObject[] _demonPrefabs;
    private Demon _currentDemon;

    // Use this for initialization
    void Start()
    {

    }

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

    }

    public void Init(int maxRitualLevel, int startRitualLevel, GameObject[] demonPrefabs)
    {
        _demonPrefabs = demonPrefabs;
        _markers = new SummonMarker[maxRitualLevel];

        var scaleDelta = MaxMarkerScale - MinMarkerScale;

        for (int i = 0; i < maxRitualLevel; i++)
        {
            int markerIndex = Random.Range(0, MarkerPrefabs.Length);
            var marker = Instantiate(MarkerPrefabs[markerIndex]).GetComponent<SummonMarker>();
            marker.transform.SetParent(transform, false);

            var positionDelta = (Mathf.PI * 2 * i) / maxRitualLevel;
            var xPos = Mathf.Sin(positionDelta) * RadiusX;
            var yDelta = Mathf.Cos(positionDelta);  
            var yPos = yDelta * RadiusY;
            var scale = MaxMarkerScale - (((yDelta + 1) / 2) * scaleDelta);

            marker.transform.localPosition = new Vector3(xPos, yPos, -RadiusY - 0.01f + (yPos * 0.01f));
            marker.transform.localScale = new Vector3(scale, scale, scale);

            _markers[i] = marker;
        }

        SpawnNewDemon();
    }

    public void SetRitualLevel(int level)
    {
        for (int i = 0; i < _markers.Length; i++)
        {
            _markers[i].SetState((i < level) ? SummonMarker.State.Ignighted : SummonMarker.State.Idle);
        }
    }

    public void SpawnNewDemon()
    {
        if (_currentDemon != null)
        {
            Destroy(_currentDemon);
        }

        int demonIndex = Random.Range(0, _demonPrefabs.Length);
        _currentDemon = Instantiate(_demonPrefabs[demonIndex]).GetComponent<Demon>();
        _currentDemon.transform.SetParent(transform, false);
    }

    public Demon GetDemon()
    {
        return _currentDemon;
    }
}
