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

public class PlayerController : MonoBehaviour
{
    Rigidbody2D rb;            // 리디즈바디형 변수
    float axisH = 0.0f;        // 키보드 좌우방향 입력
    public float speed = 3.0f; // 이동속도
    public float jump = 9.0f;  // 점프력

    public LayerMask groundLayer; // 착지할 수 있는 지면 레이어형 변수

    bool goJump = false;   // 점프 개시 플래그
    bool onGround = false; // 지면에 서 있는 플래그

    // 애니메이션처리
    Animator animator;     // 애니메이터 컴포넌트형 변수
    public string stopAnime = "PlayerStop";
    public string moveAnime = "PlayerMove";
    public string jumpAnime = "PlayerJump";
    public string goalAnime = "PlayerGoal";
    public string deadAnime = "PlayerOver";

    string nowAnime = "";
    string oldAnime = "";

    // 게임상태 저장
    // 플레이 하는 중이 아니면 '플레이어 조작' 등의
    // 처리를 하지 않게
    public static string gameState = "playing";


    void Start()
    {
        // 리지드바디 컴포넌트 가져오기
        rb = GetComponent<Rigidbody2D>();
        // 충돌시 회전 금지
        rb.constraints = RigidbodyConstraints2D.FreezeRotation; // rb.freezeRotation = true;

        // 애니메이션 처리
        animator = GetComponent<Animator>();
        nowAnime = stopAnime;
        oldAnime = stopAnime;

        gameState = "playing"; // 게임중(초기화상태)
    }

    // 키보드가 계속 눌렸는지 감지(물리력없음)
    void Update()
    {
        // 게임 상태가 플레이 중이 아니면 즉시 메서드동작을 중단
        if (gameState != "playing")
        {
            return;
        }

        axisH = Input.GetAxisRaw("Horizontal"); // +1, -1, 0 중에 하나
        if (axisH > 0)
        {
            transform.localScale = new Vector2(1, 1);
        }
        else if (axisH < 0)
        {
            transform.localScale = new Vector3(-1, 1); // 좌우반전
        }
        if (Input.GetButtonDown("Jump"))
        {
            Jump();
        }
    }

    // 실제 이동(물리력)
    void FixedUpdate()
    {
        // 게임 상태가 플레이 중이 아니면 즉시 메서드동작을 중단
        if (gameState != "playing")
        {
            return;
        }

        // 착지 판정
        onGround = Physics2D.Linecast(transform.position, transform.position - (transform.up * 0.1f), groundLayer);

        // 지면위에 있을 때(onGround가 참일때) 또는(||) 좌우방향키 눌렸을때 - 좌우이동 가능
        // 지면위에 있으면서 점프키가 눌렸을 때 - 점프가능
        if (onGround || axisH != 0)
        {
            rb.velocity = new Vector2(axisH * speed, rb.velocity.y);
        }
        if (onGround && goJump)
        {
            rb.AddForce(new Vector2(0, jump), ForceMode2D.Impulse);
            goJump = false;
        }
        if (onGround) // 지면위-대기, 이동
        {
            if (axisH == 0)
            {
                nowAnime = stopAnime;
            }
            else
            {
                nowAnime = moveAnime;
            }
        }
        else // 공중에 있을때-점프
        {
            nowAnime = jumpAnime;
        }
        if (nowAnime != oldAnime)
        {
            oldAnime = nowAnime;
            animator.Play(nowAnime);    // 애니메이션 재생
        }
    }

    // 점프
    void Jump()
    {
        goJump = true;
    }

    // 접촉 시작
    void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Goal")
        {
            Goal();
        }
        else if (collision.gameObject.tag == "Dead")
        {
            GameOver();
        }
    }


    // 게임클리어일때
    void Goal()
    {
        animator.Play(goalAnime);
        gameState = "gameClear";
        GameStop(); // 게임중지
    }

    // 게임오버일때
    void GameOver()
    {
        animator.Play(deadAnime);
        gameState = "gameOver";
        GameStop(); // 게임중지
        // 게임오버시 동작 추가
        // 데드영역에 닿으면 조금 위로 튀어올랐다가 떨어지기
        // 데드영역 충돌감지 판정을 비활성화하기
        GetComponent<CapsuleCollider2D>().enabled = false;
        rb.AddForce(new Vector2(0, 5), ForceMode2D.Impulse);
    }

    // 게임중지
    void GameStop()
    {
        gameState = "gameEnd";
        Rigidbody2D rb = GetComponent<Rigidbody2D>();
        rb.velocity = new Vector2(0, 0);
    }
}