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

public class Game11 : MonoBehaviour{

    public GameObject death1;
    public GameObject death2;
    public Transform target;
    public float speed;
    bool canMove = true;
    Vector3 start, end;

    // Start is called before the first frame update
    void Start(){
        if (target != null){
            target.parent = null;
            start = transform.position;
            end = target.position;
        }
    }

    // Update is called once per frame
    void FixedUpdate(){
        if (target != null){
            if (canMove){
                float fixedSpeed = speed * Time.fixedDeltaTime;
                transform.position = Vector3.MoveTowards(transform.position, target.position, fixedSpeed);
            }
        }

        if (transform.position == target.position){
            target.position = (target.position == start) ? end : start;
        }
    }

    void OnTriggerStay2D(Collider2D col){
        if (Input.GetKeyDown(KeyCode.Space)){
            if(col.gameObject.tag == "Finish"){
                if(transform.position.y > 0){
                    StartCoroutine(Death1());
                    Time.timeScale = 0f;
                }else{
                    StartCoroutine(Death2());
                    Time.timeScale = 0f;
                }
            }else{
                FindObjectOfType<GameController>().CompleteLevel();
                col.enabled = false;
            }
        }
    }

    IEnumerator Death1(){
        yield return new WaitForSecondsRealtime(.5f);
        death1.SetActive(true);
        yield return new WaitForSecondsRealtime(3f);
        AudioManager.instance.Play("Explosion");
        yield return new WaitForSecondsRealtime(1f);
        FindObjectOfType<GameController>().LoseGame();
    }

    IEnumerator Death2(){
        yield return new WaitForSecondsRealtime(.5f);
        death2.SetActive(true);
        yield return new WaitForSecondsRealtime(3f);
        AudioManager.instance.Play("Explosion");
        yield return new WaitForSecondsRealtime(1f);
        FindObjectOfType<GameController>().LoseGame();
    }
}
