#include <state.h>
#include <string.h>
#ifdef __windows__
#include <windows.h>
#else
#include <sys/stat.h>
#endif

void state_save(save_state* state) {
    printf("Saving state\n");
    cpu_save_state(&state->cpu);
    ram_save_state(&state->ram);
    ppu_save_state(&state->ppu);
    lcd_save_state(&state->lcd); 
    dma_save_state(&state->dma);
    timer_save_state(&state->timer);
    audio_save_state(&state->audio);
    gamepad_save_state(&state->ctlr);
    cart_save_state(&state->cart);
}

void state_load(const save_state* state) {
    printf("Loading state\n");
    cpu_load_state(&state->cpu);
    ram_load_state(&state->ram);
    ppu_load_state(&state->ppu);
    lcd_load_state(&state->lcd);
    dma_load_state(&state->dma);
    timer_load_state(&state->timer);
    audio_load_state(&state->audio);
    gamepad_load_state(&state->ctlr);
    cart_load_state(&state->cart);
}

void state_save_file(u8 slot) {
    save_state* state = malloc(sizeof(*state));
    state_save(state);
    char *filename = strrchr(cart_get_context()->filename, '\\');
    filename++;
    char fn[1048];
#ifdef __windows__
    char *profile = getenv("USERPROFILE");
    sprintf(fn, "%s/Documents/gbemu/states/%s", profile, filename);
    CreateDirectory(fn, NULL);
    sprintf(fn, "%s/Documents/gbemu/states/%s/%d.state", profile, filename, slot);
#else
    char *profile = getenv("HOME");
    sprintf(fn, "%s/.config/gbemu/states/%s", profile, filename);
    mkdir(fn, 0755);
    sprintf(fn, "%s/.config/gbemu/states/%s/%d.state", profile, filename, slot);
#endif
    FILE *fp = fopen(fn, "wb");

    if(!fp) {
        fprintf(stderr, "unable to save state %d\n", slot);
        return;
    }

    fwrite(state, sizeof(*state), 1, fp);
    fclose(fp);
}

void state_load_file(u8 slot) {
    save_state* state = malloc(sizeof(*state));
    char *filename = strrchr(cart_get_context()->filename, '\\');
    filename++;
    char fn[1048];
#ifdef __windows__
    char *profile = getenv("USERPROFILE");
    sprintf(fn, "%s/Documents/gbemu/states/%s/%d.state", profile, filename, slot);
#else
    char *profile = getenv("HOME");
    sprintf(fn, "%s/.config/gbemu/states/%s/%d.state", profile, filename, slot);
#endif
    FILE *fp = fopen(fn, "rb");

    if(!fp) {
        printf("Save slot %d doesnt exist.\n", slot);
        return;
    }

    fread(state, sizeof(*state), 1, fp);
    fclose(fp);
    state_load(state);
}
