#import "Camera.h"
#import "properties.h"

//"fixes" a weird bug with calling GetRayCollisionBox inside a method
RayCollision ObjectiveCBugFixRaycast(Camera3D camera, BoundingBox bbox) {
    Vector3 direction = Vector3Subtract(camera.target, camera.position);
    direction = Vector3Normalize(direction);
    RayCollision rc = GetRayCollisionBox((Ray){camera.position, direction}, bbox);
    return rc;
}

@implementation GameCamera

-(id) init {
    if ((self = [super init])) {
        camera.position = (Vector3){0.0f, 2.0f, 0.0f};
        camera.target = (Vector3){0.0f, 0.0f, 1.0f};
        camera.up = (Vector3){0.0f, 1.0f, 0.0f};
        camera.fovy = 90.0f;
        camera.projection = CAMERA_PERSPECTIVE;
        mode = CAMERA_CUSTOM;

        crosshair = (Vector2){default_properties.width/2, default_properties.height/2};
        crosshairColor = WHITE;
        crosshairSize = 2.0f;
    }

    return self;
}

-(void) update {
    Vector2 mouseDelta = GetMouseDelta();

    CameraYaw(&camera, -mouseDelta.x * 0.008, false);
    CameraPitch(&camera, -mouseDelta.y * 0.008, true, false, false);

    //camera.position = [attachedPlayer pos];
}

-(void) attach: (Player *) player {
    attachedPlayer = player;
    attachedPlayer->attachedCamera = self;
    //[attachedPlayer setAttachedCamera: self];
}

-(void) showPos {
    char buffer[50];
    sprintf(buffer, "pos: (%.02f, %.02f, %.02f)", camera.position.x, camera.position.y, camera.position.z);
    DrawText(buffer, 0, 0, 20, BLACK);
}

-(void) showTarget {
    char buffer[50];
    sprintf(buffer, "tgt: (%.02f, %.02f, %.02f)", camera.target.x, camera.target.y, camera.target.z);
    DrawText(buffer, 0, 30, 20, BLACK);
}

-(void) drawCrosshair {
    DrawCircleV(crosshair, crosshairSize, crosshairColor);
}

-(void) drawWeapon {
    if (attachedPlayer != NULL) {
        Texture2D texture = attachedPlayer->weapon;
        DrawTexture(texture, 0.0f, 0.0f, WHITE);
    }
}

-(bool) raycast: (BoundingBox) bbox {
    
    //i called them both raycast to maximize confusion
    if ( ObjectiveCBugFixRaycast(camera, bbox).hit ) {
        crosshairColor = RED;
    } else {
        crosshairColor = WHITE;
    }

    return ObjectiveCBugFixRaycast(camera, bbox).hit;
}

-(Camera3D *) addressOfCamera {
    return &camera;
}

@end