package me.hammerle.supersnuvi.entity.components.ai;

import me.hammerle.supersnuvi.entity.Entity;
import me.hammerle.supersnuvi.tiles.Location;
import me.hammerle.supersnuvi.util.Face;

public class FollowHeroController extends EntityController
{
    private final double motion;
    private boolean jump;
    
    public FollowHeroController(Entity ent, double motion)
    {
        super(ent);
        this.motion = motion;
        this.jump = false;
    }

    @Override
    public void tick() 
    {
        Entity hero = ent.getLevel().getHero();
        if(hero.squaredDistance(ent) <= 102400)
        {
            if(jump)
            {
                jump = false;
                ent.getMovement().jump();
            }
            double distance = ent.signedDistanceX(hero);
            if(distance < 0)
            {
                ent.setMotionX(motion * ent.getMovementPenalty().getFactor());
            }
            else if(distance > 0)
            {
                ent.setMotionX(-motion * ent.getMovementPenalty().getFactor());
            }
        }
    }

    @Override
    public void onCollideWithEntity(Entity ent, Face face) 
    {
        if(this.ent.signedDistanceX(ent) == 0)
        {
            if(ent.getX() - this.ent.getX() > 0)
            {
                ent.setMotionX(6.0);
            }
            else
            {
                ent.setMotionX(-6.0);
            }
            ent.getHealth().addHealth(-0.05);
        }
    }

    @Override
    public void onCollideWithTile(Location loc, Face face) 
    {
        if((face == Face.LEFT || face == Face.RIGHT) && 
                Math.abs(ent.getPreviousMotionX() - ent.getMotionX()) > 0.001 &&
                Math.abs(ent.signedDistanceX(ent.getLevel().getHero())) > 0.001)
        {
            jump = true;
        }
    }
}
