package com.jan.Collision;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.jan.entity.GameObject;
import com.jan.game.Display;
import com.badlogic.gdx.physics.box2d.PolygonShape;

public class Colider {
    public static final String BODY_PROPERTY = "BodyType";
    public static final String BODY_COLLIDER = "Colider";

    private Body body;
    private GameObject target;

    private String bodyType;
    private String colider;
    private boolean isSolid = true;

    public Colider(GameObject target, String bodyType, String colider, boolean isSolid){
        this(target,  bodyType,  colider);
        this.isSolid = isSolid;
    }
    public Colider(GameObject target, String bodyType, String colider){
        this.target = target;
        this.bodyType = bodyType;
        this.colider = colider;
    }

    public void loadBody(World world){
        BodyDef bodyDef = new BodyDef();
        bodyDef.type = getType(bodyType);
        float scale = Display.getScale();
        bodyDef.position.set((target.getX() + (target.getWidth() /2)) / scale, (target.getY() + (target.getHeight() /2)) /scale);
        body = world.createBody(bodyDef);
        body.setUserData(this);
        getColider();
    }

    public BodyType getType(String bodyType){
        switch(bodyType){
            case "Dynamic": return BodyType.DynamicBody;
            case "Static": return BodyType.StaticBody;
            case "Kinematic": return BodyType.KinematicBody;
        }
        return BodyType.StaticBody;
    }

    private void getColider(){
        float scale = Display.getScale();
        if(colider.equals("auto")){
            PolygonShape groundBox = new PolygonShape();  
            groundBox.setAsBox((target.getWidth() / scale) /2, (target.getHeight() / scale) /2);
            FixtureDef fixture = new FixtureDef();
            fixture.shape = groundBox;
            fixture.isSensor = !isSolid;
            body.createFixture(fixture);
            groundBox.dispose();
        }
    }

    public void updatePos(){
        Vector2 pos = body.getPosition();
        float scale = Display.getScale();
        target.setX((pos.x * scale) - target.getWidth() / 2);
        target.setY((pos.y * scale) - target.getHeight() / 2);
    }

    public Body getBody(){ return body; }
    public GameObject getEntity(){return target;}
}
