using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

public class Switch : MonoBehaviour {
  public Doors doors;
  public AudioClip pressClip, unpressClip;
  public AudioSource source;
  public bool isHeavySwitch;
  public float travelDistance = 0.05f;
  public bool doorIsFar;

  public Switch PairedSwitch;

  public bool WasActivated { get; private set; }

  private int pressCount = 0;
  private bool IsPressed { get { return pressCount > 0; } }

  private void OnTriggerEnter(Collider other) {
    var playerController = other.GetComponent<PlayerController>();
    if (playerController != null) {
      playerController.HandleSwitch(this);
    }

    var golem = other.GetComponent<GolemController>();
    if (golem != null) {
      golem.HandleSwitch(this);
    }
  }

  private void OnTriggerExit(Collider other) {
    var playerController = other.GetComponent<PlayerController>();
    if (playerController != null) {
      playerController.HandleLeaveSwitch(this);
    }
    var golem = other.GetComponent<GolemController>();
    if (golem != null) {
      golem.HandleLeaveSwitch(this);
    }
  }


  public void Press() {
    if (WasActivated) {
      return;
    }
    var playSound = !IsPressed;
    pressCount++;
    transform.DOLocalMoveY(transform.localPosition.y, 1f).OnComplete(HandlePressFinished);
    if (playSound) {
      source.PlayOneShot(pressClip);
    }
  }

  public void Unpress() {
    if (WasActivated) {
      return;
    }
    pressCount--;
    var playSound = !IsPressed;
    if (playSound) {
      source.PlayOneShot(unpressClip);
    }
  }

  private void HandlePressFinished() {
    if (PairedSwitch != null) {
      // Check pair.
      if (!PairedSwitch.IsPressed) {
        UI.Instance.ShowInfo("The switch moved but nothing happened...");
        return;
      }
    }
    Activate();
  }

  private void Activate() {
    WasActivated = true;
    if (PairedSwitch != null) {
      PairedSwitch.WasActivated = true;
    }
    if (doors != null) {
      doors.Open();
    }
    if (doorIsFar) {
      UI.Instance.ShowInfo("You hear the distant sound of rocks moving.");
    }
  }
}
