package electrosphere.game.client.targeting.crosshair;

import electrosphere.entity.Entity;
import electrosphere.entity.EntityUtils;
import electrosphere.main.Globals;
import org.joml.Vector3d;

/**
 *
 * @author amaterasu
 */
public class Crosshair {
    
    static Entity crossHairEntity;
    static float rotationTheta = 0;
    static float bobTheta = 0;
    static float bobMagnitude = 0.1f;
    static float offsetVertical = 1;
    static Entity currentTarget = null;
    
    public static void initCrossHairEntity(){
        crossHairEntity = EntityUtils.spawnDrawableEntity("/Models/lockoncrosshair1.fbx");
        EntityUtils.setVisible(crossHairEntity, false);
    }
    
    
    static final float TARGET_MAX_DIST = 1;
    public static void checkTargetable(){
        if(crossHairEntity != null && Globals.playerCharacter != null){
            Vector3d parentPos = EntityUtils.getPosition(Globals.playerCharacter);
            if(currentTarget == null){
                Entity target = null;
                double dist = 100;
                for(Entity entity : Globals.entityManager.getTargetables()){
                    double currentDist = parentPos.distance(EntityUtils.getPosition(entity));
                     if(currentDist < dist && currentDist <= TARGET_MAX_DIST && entity != Globals.playerCharacter){
                         target = entity;
                         dist = currentDist;
                     }
                }
                if(target != null){
//                    System.out.println("Found target!");
                    currentTarget = target;
                    EntityUtils.setVisible(crossHairEntity, true);
                }
            } else {
                if(parentPos.distance(EntityUtils.getPosition(currentTarget)) > TARGET_MAX_DIST){
                    currentTarget = null;
                    EntityUtils.setVisible(crossHairEntity, false);
                }
            }
        }
    }
    
    public static void updateTargetCrosshairPosition(){
        if(crossHairEntity != null && currentTarget != null){
            rotationTheta += 0.01;
            if(rotationTheta > Math.PI * 2){
                rotationTheta = 0;
            }
            bobTheta += 0.01;
            if(bobTheta > Math.PI * 2){
                bobTheta = 0;
            }
            Vector3d crosshairPos = EntityUtils.getPosition(crossHairEntity);
            crosshairPos.set(new Vector3d(EntityUtils.getPosition(currentTarget)).add(0,offsetVertical + Math.sin(bobTheta) * bobMagnitude,0));
//            EntityUtils.getRotation(crossHairEntity).rotationZ(rotationTheta);
            EntityUtils.getRotation(crossHairEntity).rotationXYZ((float)-Math.PI/2.0f, 0, rotationTheta);
        }
    }
    
    
}
