/*---------------------------------------------------------------------------*
  Project:  NitroSDK - Sample DS Viewer
  File:     main.c

  Copyright 2003-2006 Nintendo.  All rights reserved.
  Copyright 2007 BroadOn Communications Corp.  All rights reserved.

  These coded instructions, statements, and computer programs contain
  proprietary information of Nintendo of America Inc. and/or Nintendo
  Company Ltd., and are protected by Federal copyright law.  They may
  not be disclosed to third parties or copied or duplicated in any form,
  in whole or in part, without the prior written consent of Nintendo.

  $Id: main.c,v 1.12 2007/05/14 23:13:19 paulm Exp $
 *---------------------------------------------------------------------------*/


#include <nitro.h>
#include <nitro/card.h>
#include <nitro/fs.h>
#include <string.h>
#include "fs.h"
#include "es.h"

#ifdef P2P_LIB
#include "p2p.h"
#endif


/* routine for screen rendering*/
#include "draw.h"

#define USB_DEBUG
#ifdef USB_DEBUG
#define LOGPRINT(s, args...)	printf(s, ## args)
#else
#define LOGPRINT(s, args...)	OS_Printf(s, ## args)
#endif

/*---------------------------------------------------------------------------*
  Name:         VBlankIntr

  Description:  V-blank callback

  Arguments:    None.

  Returns:      None.
 *---------------------------------------------------------------------------*/
static void
VBlankIntr(void)
{
    OS_SetIrqCheckFlag(OS_IE_V_BLANK);
}

/*---------------------------------------------------------------------------*
  Name:         InitApp

  Description:  OS etc., application base part initialization

  Arguments:    None.

  Returns:      None.
 *---------------------------------------------------------------------------*/
static void
InitApp(void)
{
    void   *tmp;
    OSHeapHandle hh;

    /* OS initialization*/
    OS_Init();
    OS_InitThread();
    OS_InitTick();
    /* arena initialization*/
    tmp = OS_InitAlloc(OS_ARENA_MAIN, OS_GetMainArenaLo(), OS_GetMainArenaHi(), 1);
    OS_SetArenaLo(OS_ARENA_MAIN, tmp);
    hh = OS_CreateHeap(OS_ARENA_MAIN, OS_GetMainArenaLo(), OS_GetMainArenaHi());
    if (hh < 0)
        OS_Panic("ARM9: Fail to create heap...\n");
    hh = OS_SetCurrentHeap(OS_ARENA_MAIN, hh);
    /* Enable interrupts*/
    OS_SetIrqFunction(OS_IE_V_BLANK, VBlankIntr);
    (void)OS_EnableIrqMask(OS_IE_V_BLANK);
    (void)OS_EnableIrq();
}

u8 readBuf[16*1024];
u32 numTitles;
u32 numTickets;
u32 numTitlesOnCard;
char meta[64];
ESTitleId titleId;
ESTmdView tmdView;
char dataDirBuf[ISFS_PATH_MAXLEN];

#define MAX_TITLES 16

ESTitleType ttype[MAX_TITLES];
ESTicketView *tickets[MAX_TITLES];
u32 titleCnt = 0;
u32 numMain = 0;

int titleColor[] = { RGB555_WHITE, RGB555_BLUE, RGB555_GREEN };

#define tidHi(a) (u32)((a >> 32) & 0xffffffff)
#define tidLo(a) (u32)(a & 0xffffffff)

/*
 * Draw on the screen the titles that are on the card and
 * their ticket id's by reading
 * the title name from the file system file:
 * '/meta/[title id high]/[title id low]/title.met'
 * and the ticket id from the 'tickets' array.
 */
static void
drawTitles(void)
{
    ESTitleId *p;
    IOSFd fd;
    u32 idH, idL;
    int i;
    char metaPath[] = ES_META_FILE;
    int x = 1, y = 1;

    ClearFrame(0);
    DrawBegin();

    SetTextColor(RGB555_BLUE);
    DrawText((32-sizeof("Sample Viewer"))/2*10, 0, "Sample Viewer");
    DrawText(10, 180, "Press A to launch");

    p = (ESTitleId *)(readBuf + numTitles*sizeof(ESTitleId));

    for (i=0; i<numTitlesOnCard; ++i) {
        
        idH = tidHi(p[i]);
        idL = tidLo(p[i]);
        snprintf(metaPath, ISFS_PATH_MAXLEN, "/meta/%08x/%08x/title.met", 
                 idH, idL);
        fd = ISFS_Open((u8*)metaPath, ISFS_READ_ACCESS);
        if (fd >= 0) {
            ISFSError     bytesRead;

            bytesRead = ISFS_Read(fd, (u8*)meta, 64);
            ISFS_Close(fd);
            /* null terminate the string */
            if (bytesRead >= 0) {
                meta[bytesRead] = 0;
            }
        } else  {
            snprintf(meta, sizeof(meta), "%08x", idL);
        }

        SetTextColor(titleColor[ttype[i]]);
        DrawText(x*10, y*10, "%c%s", numMain == i ? '>' : ' ', meta);

        SetTextColor(RGB555_WHITE);
        DrawText(x*10+100, y*10, "t%08x", tickets[i]->ticketId);

        ++y;
    }
    DrawEnd();

}

static void
listTitles()
{
    u32 i, cnt=0;
    u32 idH, idL;
    ESError esErr;
    ESTicketView *t;
    u32 tmdSize;
    ESTitleId *p;

    memset(readBuf, 0, 16*1024);
    titleCnt = 0;
    esErr = ES_ListOwnedTitles(NULL, &numTitles);
    LOGPRINT("OwnedTitles: rc = %d, numTitles = %d\n", esErr, numTitles);
    esErr = ES_ListOwnedTitles((ESTitleId *)readBuf, &numTitles);
    esErr = ES_ListTitlesOnCard(NULL, &numTitlesOnCard);
    esErr = ES_ListTitlesOnCard((ESTitleId *)(readBuf+numTitles*sizeof(ESTitleId)),
                                 &numTitlesOnCard);
    LOGPRINT("TitlesOnCard: rc = %d, numTitles = %d\n", esErr, numTitlesOnCard);
    if (numTitlesOnCard > MAX_TITLES) {
        numTitlesOnCard = MAX_TITLES;
        LOGPRINT("Limit numTitlesOnCard to %d\n", MAX_TITLES);
    }

    LOGPRINT("Call ES_GetTitleId\n");
    esErr = ES_GetTitleId(&titleId);
    idH = tidHi(titleId);
    idL = tidLo(titleId);
    LOGPRINT("ES_GetTitleId returns %08x:%08x\n", idH, idL);
    esErr = ES_GetDataDir(titleId, dataDirBuf);
    LOGPRINT("ES_GetDataDir returns %s (%d)\n", dataDirBuf, esErr);
    t = (ESTicketView *)((u32*)(readBuf + (numTitles+numTitlesOnCard)*sizeof(ESTitleId)));
    p = (ESTitleId *)(readBuf + numTitles*sizeof(ESTitleId));
    for (i=0; i<numTitlesOnCard; ++i) {
        esErr = ES_GetTicketViews(p[i], NULL, &numTickets);
        ES_GetTicketViews(p[i], t, &numTickets);
        LOGPRINT("Title %08x:%08x has %d tickets\n", 
            tidHi(p[i]), tidLo(p[i]), numTickets);
        tickets[titleCnt] = t++;
        esErr = ES_GetTmdView(p[i], NULL, &tmdSize);
        esErr = ES_GetTmdView(p[i], &tmdView, &tmdSize);
        if (tmdView.head.type <= ES_TITLE_TYPE_DS_TITLE)
            ttype[titleCnt] = tmdView.head.type;
        LOGPRINT("Title %08x:%08x type %d\n", 
            tidHi(p[i]), tidLo(p[i]), ttype[titleCnt]);
        titleCnt++;
    }
    drawTitles();
}

void Launch(u32 base);
static void launchGbaTitle(const ESTitleId gbaGameTitleId);

/*
 * INPUTS:
 *         numMain: index corresponding to the user's choice
 */
static void
launchTitle(void)
{
    ESTitleId *p = (ESTitleId *)(readBuf + numTitles*sizeof(ESTitleId));
    ESError     esErr;
    ESTicketView *t = tickets[numMain];

    if (ttype[numMain] == ES_TITLE_TYPE_DS_TITLE) {
        LOGPRINT("Attempting Launch\n");
        esErr = ES_LaunchTitle(p[numMain], t);
        LOGPRINT("ES_LaunchTitle returned: %d\n", esErr);
        esErr = ES_CloseLib();
        LOGPRINT("ES_CloseLib returned: %d\n", esErr);
        Launch(0x08004000);
    }
    else if (ttype[numMain] == ES_TITLE_TYPE_NC_TITLE) {
        launchGbaTitle(p[numMain]);
    }
    else {
        LOGPRINT("Can't launch titles of type %u\n", ttype[numMain]);
    }
} // launchTitle

int createGbaLaunchFile(const ESTitleId gbaGameTitleId);

#define GetNcdWorkAddr() ((NVRAMConfigData *)(HW_NVRAM_USER_INFO))

static void
launchGbaTitle(const ESTitleId gbaGameTitleId)
{
    ESError esErr;
    ESTitleId tid = ES_TITLE_ID_GBA_SWITCHER_64;
    ESTicketView tView[1];
    u32 numTix;

    LOGPRINT("GBA title - Invoking GBA switcher\n");

    esErr = ES_GetTicketViews(tid, NULL, &numTix);
    if (esErr != ES_ERR_OK) {
        LOGPRINT("ES_GetTicketViews fails %d\n", esErr);
        goto out;
    }

    LOGPRINT("Found %d tickets for GBA Switcher\n", numTix);
    if (numTix > sizeof(tView)/sizeof(tView[0])) {
        LOGPRINT("Too many for buffer ...\n");
        numTix = sizeof(tView)/sizeof(tView[0]);
    } else if (numTix == 0) {
        LOGPRINT("GBA switch ticket missing ...\n");
        goto out;
    }

    esErr = ES_GetTicketViews(tid, tView, &numTix);
    if (esErr != ES_ERR_OK) {
        LOGPRINT("ES_GetTicketViews fails %d\n", esErr);
        goto out;
    }

    LOGPRINT("Read %d tickets for GBA Switcher\n", numTix);

    LOGPRINT("Calling ES_LaunchTitle ...\n");
    esErr = ES_LaunchTitle(tid, &tView[0]);
    if (esErr != ES_ERR_OK) {
        LOGPRINT("ES_LaunchTitle fails %d\n", esErr);
        goto out;
    }

    /*
     * Now that we're pretty sure the operation will succeed,
     * setup the screens for GBA and write the title ID of the
     * requested game to the file that the GBA viewer will read.
     *
     * Turn off the non-GBA screen here.  Turning off the screen
     * in the gba switcher breaks going into GBA mode.
     */
    PM_Init();

    if (GetNcdWorkAddr()->option.agbLcd) {
        (void) PM_SetBackLight(PM_LCD_TOP, PM_BACKLIGHT_OFF);
        LOGPRINT("Bottom screen active\n");
    }
    else {
        (void) PM_SetBackLight(PM_LCD_BOTTOM, PM_BACKLIGHT_OFF);
        LOGPRINT("Top screen active\n");
    }

    if (createGbaLaunchFile(gbaGameTitleId) != 0) {
        return;
    }

    ES_CloseLib();
    LOGPRINT("Invoke the loaded code ...\n");
    Launch(0x08004000);
    
    LOGPRINT("NOTREACHED?\n");

out:
    LOGPRINT("GBA launch failed\n");
} // launchGbaTitle


static int
createGbaLaunchFile(const ESTitleId gbaGameTitleId)
{
    ISFSError           fsError;
    IOSFd               fileDes;

    fsError = ISFS_CreateFile((const unsigned char *) ES_GBA_LAUNCH_PATH, 0,
                              ISFS_RW_ACCESS, ISFS_RW_ACCESS, ISFS_RW_ACCESS);
    if (fsError == ISFS_ERROR_EXISTS) {
        fsError = ISFS_Delete((const unsigned char *) ES_GBA_LAUNCH_PATH);
        if (fsError != ISFS_ERROR_OK) {
            LOGPRINT("Deleting GBA launch file returned: %d\n", fsError);
            return(-1);
        }
        fsError = ISFS_CreateFile((const unsigned char *) ES_GBA_LAUNCH_PATH, 0,
                                  ISFS_RW_ACCESS, ISFS_RW_ACCESS, ISFS_RW_ACCESS);
    }

    if (fsError != ISFS_ERROR_OK) {
        LOGPRINT("Error: Creating launch file returned: %d\n", fsError);
        return(-1);
    }
    fileDes = ISFS_Open((const unsigned char *) ES_GBA_LAUNCH_PATH, 
                         ISFS_RW_ACCESS);
    if (fileDes < 0) {
        LOGPRINT("Error: Opening launch file returned: %d\n", fileDes);
        return(-1);
    }

    /*
    LOGPRINT("%s: Writing title id 0x%llx to file\n", __FUNCTION__,
              gbaGameTitleId);
    */

    fsError = ISFS_Write(fileDes, (unsigned char *) &gbaGameTitleId,
                         sizeof(ESTitleId));
    if (fsError != sizeof(ESTitleId)) {
        LOGPRINT("Error: Writing GBA game title id returned: %d\n", fsError);
        return(-1);
    }

    fsError = ISFS_Close(fileDes);
    if (fsError != ISFS_ERROR_OK) {
        LOGPRINT("Error: Closing GBA launch file returned: %d\n", fsError);
        return(-1);
    }
    return(0);
} // createGbaLaunchFile

/*---------------------------------------------------------------------------*
  Name:         NitroMain

  Description:  main entry point

  Arguments:    None.

  Returns:      None.
 *---------------------------------------------------------------------------*/
void
NitroMain(void)
{
    u32         last, r;
#ifdef P2P_LIB
    P2PErrCode  p2pErr;
#endif

    /* sample application initialization */
    InitApp();
    InitDraw();
    SetClearColor(RGB555_CLEAR);

    CTRDG_Init();
    CTRDG_Enable(TRUE);

    ES_InitLib();

#ifdef P2P_LIB
    p2pErr = P2P_Init(NULL, P2P_NOWAIT);
    if (p2pErr != P2P_OK) {
        LOGPRINT("P2P_Init failed: code is: %d\n", p2pErr);
    }
#endif

    listTitles();

    /* screen transition*/
    last = PAD_Read();
    for (;;) {
        r = PAD_Read();
        if ((r & PAD_BUTTON_A) && !(last & PAD_BUTTON_A)) {
            LOGPRINT("Calling launchTitle ...\n");
            launchTitle();
        }
        if ((r & PAD_KEY_UP) && !(last & PAD_KEY_UP)) {
            if (--numMain >= titleCnt)
                numMain = titleCnt-1;
            drawTitles();
        }
        if ((r & PAD_KEY_DOWN) && !(last & PAD_KEY_DOWN)) {
            if(++numMain == titleCnt)
                numMain=0;
            drawTitles();
        }
        last = r;
    }
}
