using UnityEngine;
using System.Collections.Generic;

[RequireComponent(typeof(Teleporter))]
public class RelinkTeleporter : MonoBehaviour, IObserver
{
    public int[] dependencies;
    public bool[] matchingStates;

    public int newTargetID;
        
    private Dictionary<int, int> _switchIndexMapping;
    private bool[] _currentState;

    private int _oldTargetID;
    private Teleporter _teleporter;

    // Use this for initialization
    void Start()
    {
        _teleporter = GetComponent<Teleporter>();
        _oldTargetID = _teleporter.targetId;

        if (dependencies.Length == 0)
        {
            _teleporter.targetId = newTargetID;
            return;
        }

        _switchIndexMapping = new Dictionary<int, int>();

        for (int i = 0; i < dependencies.Length; i++)
        {
            LevelManager.Instance.ListenForSwitch(this, dependencies[i]);
            _switchIndexMapping.Add(dependencies[i], i);
        }

        _currentState = new bool[dependencies.Length];
    }

    public void Notify(object sender)
    {
        Switch s = (Switch)sender;
        _currentState[_switchIndexMapping[s.id]] = s.IsActivated;

        bool statesMatch = MatchStates();

        if (statesMatch)
            _teleporter.targetId = newTargetID;
        else
            _teleporter.targetId = _oldTargetID;

        LevelManager.Instance.RelinkTeleporter(_teleporter);
    }

    private bool MatchStates()
    {
        bool match = true;
        for (int i = 0; i < matchingStates.Length; i++)
            match &= _currentState[i] == matchingStates[i];

        return match;
    }
}
