#import "AssetLoader.h"

@implementation AssetLoader
//@synthesize drawables;

-(id) init {
    if ((self = [super init])) {
        drawables = [[YSArray alloc] init];
    }

    return self;
}

-(void) draw {
    int i;
    for (i = 0; i < drawables->count; i++) {
        //printf("i should be drawing: %p\n", drawables->array[i]);
        [drawables->array[i] draw];
    }
    return;
}

//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;
    }

GET_PATH:
    r.path = get_next_token(buffer, ": ", 0);
    goto END;

GET_POS:
    r.pos = parse_pos( get_next_token(buffer, ": ", 0) );

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

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

    NSModel *m;

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

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

        switch (r.type) {
        case MDL:
            //suck cock
            m = [NSModel alloc];
            [m initWithModel: s];
            break;
        case TEX:
            [m setTexture: s];
            break;

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

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

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

-(void) printAllAssets {
    printf("capacity: %d\n", [drawables capacity]);
}

@end