#include "arc/graphics/spritesheet.h"

#include "spritesheet.h"
#include "renderer.h"
#include "arc/math/point.h"
#include <SDL.h>
#include <SDL_image.h>
#include <stdlib.h>

//TODO: Temp function
void ARC_Spritesheet_CreateFromFile(ARC_Spritesheet **spritesheet, ARC_Renderer *renderer, ARC_String *path){
    *spritesheet = (ARC_Spritesheet *)malloc(sizeof(ARC_Spritesheet));

    IMG_Init(IMG_INIT_PNG);
    SDL_Surface *surface = IMG_Load(path->data);
    if(!surface){
        printf("Error: reading png '%s'\nSDL_Image Error: %s", path->data, IMG_GetError());
    }

    SDL_BlendMode tempMode;
    SDL_GetSurfaceBlendMode(surface, &tempMode);
    (*spritesheet)->texture = SDL_CreateTextureFromSurface((SDL_Renderer *)renderer, surface);
    SDL_GetTextureBlendMode((*spritesheet)->texture, &tempMode);

    SDL_FreeSurface(surface);
    IMG_Quit();

    ARC_Spritesheet_GetSize(*spritesheet);
}

void ARC_Spritesheet_Destroy(ARC_Spritesheet *spritesheet){
    SDL_DestroyTexture(spritesheet->texture);
    free(spritesheet);
}

void ARC_Spritesheet_RenderArea(ARC_Spritesheet *spritesheet, ARC_Rect *sheetBounds, ARC_Renderer *renderer, ARC_Rect *renderBounds){
    SDL_RenderCopy((SDL_Renderer *)renderer, spritesheet->texture, (SDL_Rect *)sheetBounds, (SDL_Rect *)renderBounds);
}

ARC_Point ARC_Spritesheet_GetSize(ARC_Spritesheet *spritesheet){
    ARC_Point size;
    SDL_QueryTexture(spritesheet->texture, NULL, NULL, &size.x, &size.y);
    return size;
}

uint32_t *ARC_Spritesheet_GetTileSize(ARC_Spritesheet *spritesheet){
    return spritesheet->size;
}
