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

/// <summary>
/// Logic block which deals with moving a character in a direction
/// </summary>
[CreateAssetMenu(menuName = "Major Project/Move Block")]
[System.Serializable]
public class Move : LogicBlock
{

    [SerializeField]
    protected Direction direction = Direction.Forward;

    #region Class Functions

    /// <summary>
    /// Implementation of BlockLogic, moves the player forward
    /// </summary>
    /// <param name="player">Player to move</param>
    protected override IEnumerator BlockLogic(Character player, float animationTime, bool useBlockDirection = false)
    {
        player.justMoved = true;

        Block endBlock;
        if (useBlockDirection)
            endBlock = GetEndBlock(player.CurrentBlock, player.CurrentBlock.transform, ~player.Ignore);
        else
            endBlock = GetEndBlock(player.CurrentBlock, player.transform, ~player.Ignore);
        

        yield return player.StartCoroutine(player.MoveToBlock(endBlock, Character.Animation.Walk, animationTime));
    }

    /// <summary>
    /// Returns the block that the character will endUp on after they use this logic element
    /// </summary>
    /// <param name="startBlock">block character is on</param>
    /// <param name="layerMask">layers to ignore</param>
    /// <returns></returns>
    public override Block GetEndBlock(Block startBlock,Transform tranform,  LayerMask layerMask)
    {

        DebugExtensions.DrawCube(startBlock.position, Vector3.one / 2, Color.red, 3, false);

        Vector3 wantedPosition = startBlock.position + direction.ToVector(tranform); // position wanted
        Block hit; //output of block detection
        Block retVal = startBlock; //Block we'll move to

        if (!Block.isBlockAtPosition(wantedPosition + Vector3.up, 1, layerMask))
            return Block.GetOrCreateBlockAtPosition(wantedPosition, 1, layerMask);
        else
            return startBlock;
    }

    public override void CopyToken(BlockToken token)
    {
        base.CopyToken(token);
        direction = ((DirectionToken)token).direction;
    }

    public override BlockToken ToToken(BlockToken token = null)
    {
        if (token == null)
            token = new DirectionToken(this);

        DirectionToken retVal = (DirectionToken) base.ToToken(token);
        retVal.direction = direction;

        return retVal;
    }

    #endregion Class Functions
}

[System.Serializable]
public class DirectionToken : BlockToken
{
    public Direction direction;

    public DirectionToken(LogicBlock block) : base(block) { }
}
