#import "AssetLoader.h"

@implementation AssetLoader
//@synthesize drawables;

//game specific parts of the parser
enum {
    MDL = 0,
    TEX = 1,
    POS = 2,
};

typedef struct Resource {
    int type;
    char *path;
    Vector3 pos;
} Resource;

Vector3 parse_pos(char *buffer) {
    Vector3 vec;
    vec.x = strtof( buffer, NULL);
    vec.y = strtof( get_next_token(buffer, ", ", 0), NULL);
    vec.z = strtof( get_next_token(buffer, ", ", 0), NULL);
    //printf("got vector: %f %f %f\n", vec.x, vec.y, vec.z);

    return vec;
}

Resource parse_line(char *buffer) {
    char *token = get_next_token(buffer, ": ", 0);

    if (token == NULL) {
        get_next_token(NULL, NULL, 1);
    }

    Resource r = {0};

    if (strcmp(token, "obj") == 0) {
        r.type = MDL;
        goto GET_PATH;
    }

    if (strcmp(token, "tex") == 0) {
        r.type = TEX;
        goto GET_PATH;
    }

    if (strcmp(token, "pos") == 0) {
        r.type = POS;
        goto GET_POS;
    }

    goto END; //debug

GET_PATH:
    r.path = get_next_token(buffer, ": ", 0);
    printf("got path: %s\n", r.path);
    goto END;

GET_POS:
    r.pos = parse_pos( get_next_token(buffer, ": ", 0) );
    printf("got pos: %f %f %f\n", r.pos.x, r.pos.y, r.pos.z);

END:
    get_next_token(NULL, NULL, 1);
    return r;
}

-(void) loadAssetFile: (const char *) path {
    char *file = load_file( path );
    char *line;
    
    char *s;

    PhysObject *m;

    for (line = get_next_line(file, 0); line != NULL; line = get_next_line(file, 0)) {
        //debug

        Resource r = {0};
        r = parse_line(line);
        
        if (r.path == NULL) {
            goto SKIP_PATH;
        }
        
        s = r.path;

        switch (r.type) {
        case MDL:
            //suck cock
            m = [PhysObject alloc];
            [m init];
            [m setModel: s];
            break;

        case TEX:
            [m setTexture: s];
            break;

        SKIP_PATH:
        case POS:
            [m setPos: r.pos];
            [self addObject: m];
            break;
        }
    }

    #ifdef DEBUG
    int i;
    for (i = 0; i < count; i++) {
        printf("%p\n", array[i]);
        printf("%f %f %f\n", [array[i] pos].x, [array[i] pos].y, [array[i] pos].z);
    }

    printf("count: %d\n", count);
    printf("capacity: %d\n", cap);
    #endif
}

-(void) sendObject: (id) obj to: (YSArray *) receiver {
    [receiver addObject: obj];
}

@end