/*
MIT License

Copyright (c) 2020-2024 Rupert Carmichael

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
 
#include <stdio.h>
#include <stdint.h>

#include "vecx.h"
#include "vecx_mixer.h"
#include "vecx_render.h"
#include "version.h"

#include <jg/jg.h>
#include <jg/jg_vectrex.h>
#if JG_VERSION_NUMBER < 10100
#include "jg_compat.h"
#endif

#define SAMPLERATE 48000
#define FRAMERATE 50
#define CHANNELS 1
#define NUMINPUTS 2

static jg_cb_audio_t jg_cb_audio;
static jg_cb_frametime_t jg_cb_frametime;
static jg_cb_log_t jg_cb_log;
static jg_cb_rumble_t jg_cb_rumble;

#if JG_VERSION_NUMBER >= 10100
static void *udata_audio;
static void *udata_frametime;
static void *udata_rumble;
#endif

static jg_coreinfo_t coreinfo = {
    "vecx", "Vecx JG", JG_VERSION, "vectrex", NUMINPUTS, JG_HINT_VIDEO_PRESCALED
};

static jg_videoinfo_t vidinfo;

static jg_audioinfo_t audinfo = {
    JG_SAMPFMT_INT16,
    SAMPLERATE,
    CHANNELS,
    (SAMPLERATE / FRAMERATE) * CHANNELS,
    NULL
};

static jg_pathinfo_t pathinfo;
static jg_fileinfo_t gameinfo;
static jg_fileinfo_t biosinfo;
static jg_inputinfo_t inputinfo[NUMINPUTS];
static jg_inputinfo_t inputlist[NUMINPUTS];
static jg_inputstate_t *input_device[NUMINPUTS];

static int inputlist_built = 0;

// Emulator settings
static jg_setting_t settings_vecx[] = {
    { "linealgo", "Line Drawing Algorithm",
      "0 = Bresenham, 1 = Wu",
      "Select either Bresenham or Wu line drawing algorithm",
      0, 0, 1, 0
    },
    { "vscale", "Internal Video Scale",
      "N = Internal Video Scale",
      "Set the internal video rendering scale",
      2, 1, 5, 1
    },
};

enum {
    LINEALGO,
    VSCALE,
};

static jg_systeminfo_t systemlist[] = {
    { "vectrex", "Vectrex", "vec" },
};

// Input refresh
static void vecx_input_refresh(void) {
    // Player 1 Up/Down
    if (input_device[0]->button[0]) alg_jch1 = 0xff;
    else if (input_device[0]->button[1]) alg_jch1 = 0x00;
    else alg_jch1 = 0x80;
    
    // Player 1 Left/Right
    if (input_device[0]->button[3]) alg_jch0 = 0xff;
    else if (input_device[0]->button[2]) alg_jch0 = 0x00;
    else alg_jch0 = 0x80;
    
    // Player 2 Up/Down
    if (input_device[1]->button[0]) alg_jch3 = 0xff;
    else if (input_device[1]->button[1]) alg_jch3 = 0x00;
    else alg_jch3 = 0x80;
    
    // Player 2 Left/Right
    if (input_device[1]->button[3]) alg_jch2 = 0xff;
    else if (input_device[1]->button[2]) alg_jch2 = 0x00;
    else alg_jch2 = 0x80;

    // Buttons
    buttons = 0xff;
    
    // Player 1
    if (input_device[0]->button[4]) buttons &= ~0x01;
    if (input_device[0]->button[5]) buttons &= ~0x02;
    if (input_device[0]->button[6]) buttons &= ~0x04;
    if (input_device[0]->button[7]) buttons &= ~0x08;
    
    // Player 2
    if (input_device[1]->button[4]) buttons &= ~0x10;
    if (input_device[1]->button[5]) buttons &= ~0x20;
    if (input_device[1]->button[6]) buttons &= ~0x40;
    if (input_device[1]->button[7]) buttons &= ~0x80;
}

#if JG_VERSION_NUMBER >= 10100
static void vecx_cb_audio(size_t samps) {
    jg_cb_audio(udata_audio, samps);
}

void jg_set_cb_audio(jg_cb_audio_t func, void *ud) {
    jg_cb_audio = func;
    udata_audio = ud;
}

void jg_set_cb_frametime(jg_cb_frametime_t func, void *ud) {
    jg_cb_frametime = func;
    udata_frametime = ud;
}
#else
void jg_set_cb_audio(jg_cb_audio_t func) {
    jg_cb_audio = func;
}

void jg_set_cb_frametime(jg_cb_frametime_t func) {
    jg_cb_frametime = func;
}
#endif

void jg_set_cb_log(jg_cb_log_t func) {
    jg_cb_log = func;
}

#if JG_VERSION_NUMBER >= 10100
void jg_set_cb_rumble(jg_cb_rumble_t func, void *ud) {
    jg_cb_rumble = func;
    udata_rumble = ud;
}
#else
void jg_set_cb_rumble(jg_cb_rumble_t func) {
    jg_cb_rumble = func;
}
#endif

int jg_init(void) {
    vecx_init();
    vecx_render_set_algo(settings_vecx[LINEALGO].val);
    vecx_render_set_scale(settings_vecx[VSCALE].val);
    return 1;
}

void jg_deinit(void) {
    vecx_mixer_deinit();
    vecx_deinit();
}

void jg_reset(int hard) {
    if (hard) { } // Unused
    vecx_reset();
}

void jg_exec_frame(void) {
    vecx_input_refresh();
    vecx_emu((VECTREX_MHZ / 1000) * EMU_TIMER);
}

int jg_game_load(void) {
    // Try to load the BIOS as an auxiliary file
    if (biosinfo.size) {
        vecx_bios_load(biosinfo.data, biosinfo.size);
    }
    else { // Otherwise, use the default path
        char biospath[256];
        snprintf(biospath, sizeof(biospath), "%s/rom.dat", pathinfo.core);
        if (!vecx_bios_load_file(biospath))
            jg_cb_log(JG_LOG_ERR, "Failed to load bios %s\n", biospath);
    }
    
    // Load the ROM
    if (!vecx_rom_load(gameinfo.data, gameinfo.size))
        return 0;
    
    // Set up input devices
    inputinfo[0] = jg_vectrex_inputinfo(0, JG_VECTREX_PAD);
    inputinfo[1] = jg_vectrex_inputinfo(1, JG_VECTREX_PAD);
    
#if JG_VERSION_NUMBER >= 10100
    jg_cb_frametime(udata_frametime, FRAMERATE);
#else
    jg_cb_frametime(FRAMERATE);
#endif
    
    return 1;
}

int jg_game_unload(void) {
    return 1;
}

int jg_state_load(const char *filename) {
    return vecx_state_load(filename);
}

void jg_state_load_raw(const void *data) {
    if (data) { }
}

int jg_state_save(const char *filename) {
    return vecx_state_save(filename);
}

const void* jg_state_save_raw(void) {
    return NULL;
}

size_t jg_state_size(void) {
    return 0;
}

void jg_media_select(void) {
}

void jg_media_insert(void) {
}

void jg_media_mount(unsigned mount) {
    (void)mount;
}

void jg_media_set(unsigned id) {
    (void)id;
}

void jg_cheat_clear(void) {
}

void jg_cheat_set(const char *code) {
    if (code) { }
}

void jg_rehash(void) {
    vecx_render_set_algo(settings_vecx[LINEALGO].val);
}

void jg_data_push(uint32_t type, int port, const void *ptr, size_t size) {
    if (type || port || ptr || size) { }
}

jg_systeminfo_t* jg_get_systemlist(size_t *num) {
    *num = sizeof(systemlist) / sizeof(jg_systeminfo_t);
    return systemlist;
}

jg_coreinfo_t* jg_get_coreinfo(const char *sys) {
    if (sys) { }
    return &coreinfo;
}

jg_videoinfo_t* jg_get_videoinfo(void) {
    vidinfo = (jg_videoinfo_t){
        JG_PIXFMT_XRGB8888,
        VWIDTH * settings_vecx[VSCALE].val,
        VHEIGHT * settings_vecx[VSCALE].val,
        VWIDTH * settings_vecx[VSCALE].val,
        VHEIGHT * settings_vecx[VSCALE].val,
        0, 0,
        VWIDTH * settings_vecx[VSCALE].val,
        330.0/410.0,
        NULL
    };
    return &vidinfo;
}

jg_audioinfo_t* jg_get_audioinfo(void) {
    return &audinfo;
}

jg_inputinfo_t* jg_get_inputinfo(int port) {
    return &inputinfo[port];
}

jg_inputinfo_t* jg_get_inputlist(size_t *num) {
    if (!inputlist_built) {
        inputlist[0] = jg_vectrex_inputinfo(0, JG_VECTREX_PAD);
        inputlist[1] = jg_vectrex_inputinfo(1, JG_VECTREX_PAD);
        inputlist_built = 1;
    }
    *num = NUMINPUTS;
    return inputlist;
}

jg_setting_t* jg_get_settings(size_t *numsettings) {
    *numsettings = sizeof(settings_vecx) / sizeof(jg_setting_t);
    return settings_vecx;
}

jg_setting_t* jg_get_dips(size_t *num) {
    *num = 0;
    return NULL;
}

jg_mediainfo_t* jg_get_mediainfo(void) {
    return NULL;
}

jg_biosinfo_t* jg_get_bioslist(size_t *num) {
    *num = 0;
    return NULL;
}

void jg_setup_video(void) {
    vecx_render_set_buf(vidinfo.buf);
}

void jg_setup_audio(void) {
    vecx_mixer_set_buffer(audinfo.buf);
#if JG_VERSION_NUMBER >= 10100
    vecx_mixer_set_callback(vecx_cb_audio);
#else
    vecx_mixer_set_callback(jg_cb_audio);
#endif
    vecx_mixer_set_rate(SAMPLERATE);
    vecx_mixer_init();
}

void jg_set_inputstate(jg_inputstate_t *ptr, int port) {
    input_device[port] = ptr;
}

void jg_set_gameinfo(jg_fileinfo_t info) {
    gameinfo = info;
}

void jg_set_auxinfo(jg_fileinfo_t info, int index) {
    if (index)
        return;
    biosinfo = info;
}

void jg_set_paths(jg_pathinfo_t paths) {
    pathinfo = paths;
}

unsigned jg_api_version(void) {
    return JG_VERSION_NUMBER;
}
