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

public class BallController : MonoBehaviour {


    [SerializeField]
    Rigidbody rigidBody;

    [SerializeField]
    InputManager inputManager;

    [SerializeField]
    GameParameter gameParameter;

    [SerializeField]
    float ballZValue;

    [SerializeField]
    DeathBlowPlayer deathBlow;

    Vector3 prevMousePosition;
    bool throwflag = false;

	// Use this for initialization.
	void Start () {

        inputManager.SetExecInputPressMethod(ExecuteSetBallPosition);
        inputManager.SetExecInputDownMethod(ExecuteBallInitialize);
        inputManager.SetExecInputReleaseMethod(ExecuteThrowBall);
        inputManager.SetExecInputDeathBlowMethod(ActiveDeathBlow);
	}
	
	// Update is called once per frame.
	void Update () {

	}

    private void ExecuteBallInitialize()
    {
        rigidBody.velocity = Vector3.zero;
        Debug.Log("ボール初期化");
    }

    private void ExecuteSetBallPosition() {

        if (!throwflag) {
            prevMousePosition = Input.mousePosition;
            prevMousePosition.x -= Screen.width*0.5f;
            prevMousePosition.y -= Screen.height*0.5f;
            throwflag = true;
        }

        var throwPosition = Input.mousePosition;
        throwPosition.x -= Screen.width*0.5f;
        throwPosition.y -= Screen.height*0.5f;

        //prevMousePosition.y = 0;
        //throwPosition.y = 0;
        throwPosition -= prevMousePosition;
        throwPosition *= 0.01f;
        throwPosition.y *= gameParameter.HeightScrollPercentage;
        throwPosition.y += 0.7f;
        //throwPosition.y = 0.7f;

        var ballPosition = transform.position;
        SetThrowPosition(throwPosition);

        prevMousePosition = throwPosition;
    }

    private void ExecuteThrowBall() {

        var force = inputManager.GetFlickDirection();
        force *= gameParameter.PlayerPower;
        ThrowBall(force);
        throwflag = false;
    }


    public void SetThrowPosition(Vector3 throwPosition) {

        throwPosition.z = ballZValue;
        transform.position = throwPosition;
    }


    private void ThrowBall(Vector3 force) {

        rigidBody.AddForce(force);
    }

    public void ActiveDeathBlow()
    {
        if (gameParameter.DeathBlowCredit >= 1)
        {
            deathBlow.Play();
        }
        gameParameter.DeathBlowCredit--;
    }


}





