/////////////////////////////////////////////////////////////////////////////
// Name:        TitanApp.cpp
// Purpose:     
// Author:      Vince Harron
// Modified by: 
// Created:     06/07/05 12:52:55
// RCS-ID:      
// Copyright:   2005 Sony Online Entertainment
// Licence:     
/////////////////////////////////////////////////////////////////////////////

#if defined(__GNUG__) && !defined(__APPLE__)
    #pragma implementation "TitanApp.h"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
#pragma hdrstop
#endif

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

////@begin includes
////@end includes

#include "TitanApp.h"
#include "TitanFrame.h"
#include "TitanUI.h"
#include "SyStr.h"
#include "t4.h"
#ifndef _WIN32
#include "../sys/PS3/SyCellSdkVersion.h"
#endif

    // these two functions are implemented in SyDesktop.cpp, but we can't include that header here
    // so we do this to get access to the functionality
void SyInitRecordMode(const wxChar *recordFilename);
void SyInitPlaybackMode(const wxChar *playbackFilename);
void SyInitMovieMode(const wxChar *movieFilename);
void SyInitFixedFrameMode(int fixedFrameRate);
int SyInitVideoMode(const wxChar *modeString);
void SySetButtonMapping(int deviceId, const wxChar *mapping);


////@begin XPM images
////@end XPM images

#include "wx/virtual/vdesktop.h"
#include "wx/evtloop.h"
#include "wx/cmdline.h"

/*!
 * Application instance implementation
 */

////@begin implement app
IMPLEMENT_APP( TitanApp )
////@end implement app

/*!
 * TitanApp type definition
 */

IMPLEMENT_CLASS( TitanApp, wxApp )

/*!
 * TitanApp event table definition
 */

BEGIN_EVENT_TABLE( TitanApp, wxApp )

////@begin TitanApp event table entries
////@end TitanApp event table entries
    EVT_END_SESSION( TitanApp::OnEndSession )

END_EVENT_TABLE()

/*!
 * Constructor for TitanApp
 */

TitanApp::TitanApp():
mpTitanFrame(0),
mNet(false),
mMultiPass(false),
mBloomEnabled(false),
mLog(false),
mShowUI(true),
mPawnDebug(false),
mArtCheck(true),
mPlayerModelOverload(NULL)
{
////@begin TitanApp member initialisation

  mLevelName = strdup("level_1.lvl");

  mRecordFilename[0] = 0;
  mPlaybackFilename[0] = 0;

////@end TitanApp member initialisation

  // set the locale (language-location combo) for text translation
  T4::setLocale( T4::EN_US ); // American English
}

/*!
* Destructor for TitanApp
*/
TitanApp::~TitanApp()
{
  delete mLevelName;
  delete mPlayerModelOverload;
}


/*!
 * Initialization for TitanApp
 */

bool TitanApp::OnInit()
{ 
    if ( !wxApp::OnInit() )
    {
        return false;
    }

    char netRecordFilename[256];
    char netPlaybackFilename[256];
    strcpy(netRecordFilename, mRecordFilename);
    strcpy(netPlaybackFilename, mPlaybackFilename);
    if (netRecordFilename[0] != 0)
    {
        strcat(netRecordFilename, ".net");
    }
    if (netPlaybackFilename[0] != 0)
    {
        strcat(netPlaybackFilename, ".net");
    }

    mpTitanFrame = new TitanFrame(netRecordFilename, 
                                  netPlaybackFilename, 
                                  mBloomEnabled, 
                                  mMultiPass, 
                                  mNet, 
                                  mLevelName, 
                                  mShowUI,
                                  mPawnDebug, 
                                  mArtCheck,
                                  0);

  
    mpTitanFrame->Move(0,0);
    int w;
    int h;
    wxDisplaySize( &w, &h );
    mpTitanFrame->Show();
    mpTitanFrame->SetSize( w, h );
    mpTitanFrame->SetFocus();

    mpTitanFrame->mpTitan->SetLogMode(mLog);

    if (mPlayerModelOverload != NULL)
    {
      mpTitanFrame->mpTitan->OverloadPlayerModel(mPlayerModelOverload);
    }
#if 0
////@begin TitanApp initialization
    // Remove the comment markers above and below this block
    // to make permanent changes to the code.

#if wxUSE_XPM
    wxImage::AddHandler( new wxXPMHandler );
#endif
#if wxUSE_LIBPNG
    wxImage::AddHandler( new wxPNGHandler );
#endif
#if wxUSE_LIBJPEG
    wxImage::AddHandler( new wxJPEGHandler );
#endif
#if wxUSE_GIF
    wxImage::AddHandler( new wxGIFHandler );
#endif
////@end TitanApp initialization
#endif

    return true;
}

/*!
 * Cleanup for TitanApp
 */
int TitanApp::OnExit()
{    
////@begin TitanApp cleanup
    return wxApp::OnExit();
////@end TitanApp cleanup
}

/*!
* wxEVT_END_SESSION event handler
*/

void TitanApp::OnEndSession( wxCloseEvent& event )
{
  mpTitanFrame->SetFocus();
  if ( m_mainLoop->IsRunning() )
  {
    if ( mpTitanFrame )
    {
      mpTitanFrame->Destroy();
      mpTitanFrame = 0;
    }
  }
}


static int bEnableDrawInterface = 0;
void testGlobalToggleDrawInterface()
{
  bEnableDrawInterface = !bEnableDrawInterface;
}

// Handles the frame event
// The frame event occurs after all input is processed.
void TitanApp::OnFrame()
{
  if ( mpTitanFrame )
  {
    mpTitanFrame->OnUpdateGame();
  }

  VDesktop::Get()->BeginScene();

  if ( mpTitanFrame )
  {
    mpTitanFrame->OnRenderGame();
  }
#ifndef TEMP_IGNORE_BUGS_USING_BETASDK050
  if (bEnableDrawInterface)
   VDesktop::Get()->DrawInterface();
#endif
  VDesktop::Get()->EndScene();
  VDesktop::Get()->OnFrame();
}

#define OPTION_VIDEO wxT("video")
#define OPTION_MOVIE wxT("movie")
#define OPTION_RECORD wxT("record")
#define OPTION_PLAYBACK wxT("playback")
#define OPTION_FRAMERATE wxT("framerate")
#define OPTION_NET wxT("net")
#define OPTION_MULTIPASS wxT("multipass")
#define OPTION_BLOOM wxT("bloom")
#define OPTION_LEVEL wxT("level")
#define OPTION_PS2 wxT("ps2")
#define OPTION_LOGITECH wxT("logitech")
#define OPTION_LOG wxT("log")
#define OPTION_NO_INTERFACE wxT("no_interface")
#define OPTION_PAWN_DEBUG wxT("pawn_debug")
#define OPTION_NO_ART_CHECK wxT("disable_art_check")
#define OPTION_PLAYER_MODEL wxT("player_model")


// this one is called from OnInit() to add all supported options
// to the given parser (don't forget to call the base class version if you
// override it!)
void TitanApp::OnInitCmdLine(wxCmdLineParser& parser)
{
  // first add the standard options
  wxApp::OnInitCmdLine(parser);

  // the standard command line options
  static const wxCmdLineEntryDesc cmdLineDesc[] =
  {
    {
      wxCMD_LINE_SWITCH,
      _T("n"),
      _T("net"),
      gettext_noop("operate in network mode"),
      wxCMD_LINE_VAL_NONE,
      0x0
    },

    {
      wxCMD_LINE_SWITCH,
      _T("m"),
      _T("multipass"),
      gettext_noop("turn on multipass rendering"),
      wxCMD_LINE_VAL_NONE,
      0x0
    },

    {
      wxCMD_LINE_SWITCH,
      _T(""),
      _T("bloom"),
      gettext_noop("turn on bloom rendering"),
      wxCMD_LINE_VAL_NONE,
      0x0
    },

    {
      wxCMD_LINE_OPTION,
      _T(""),
      _T("framerate"),
      gettext_noop("set game to run at a fixed logical frame rate"),
      wxCMD_LINE_VAL_NUMBER,
      0x0
    },

    {
      wxCMD_LINE_OPTION,
        _T("l"),
        _T("level"),
        gettext_noop("name of level to load (.lvl or .xml)"),
        wxCMD_LINE_VAL_STRING,
        0x0
    },

    {
      wxCMD_LINE_OPTION,
        _T(""),
        _T("record"),
        gettext_noop("record session input to a file for playback later"),
        wxCMD_LINE_VAL_STRING,
        0x0
    },

    {
      wxCMD_LINE_OPTION,
        _T(""),
        _T("movie"),
        gettext_noop("write every frame to a file to make a movie"),
        wxCMD_LINE_VAL_STRING,
        0x0
    },

    {
      wxCMD_LINE_OPTION,
        _T(""),
        _T("video"),
        gettext_noop("sets the video mode to start in (ie. resolution)"),
        wxCMD_LINE_VAL_STRING,
        0x0
    },

    {
      wxCMD_LINE_OPTION,
        _T(""),
        _T("playback"),
        gettext_noop("playback a previously recorded session"),
        wxCMD_LINE_VAL_STRING,
        0x0
    },

    {
        wxCMD_LINE_SWITCH,
        _T(""),
        _T("ps2"),
        gettext_noop("use ps2 controller button settings"),
        wxCMD_LINE_VAL_NONE,
        0x0
    },
    {
      wxCMD_LINE_SWITCH,
        _T(""),
        _T("logitech"),
        gettext_noop("use Logitech Dual Action controller settings"),
        wxCMD_LINE_VAL_NONE,
        0x0
    },
    {
      wxCMD_LINE_SWITCH,
        _T(""),
        _T("log"),
        gettext_noop("log combat results to log.txt"),
        wxCMD_LINE_VAL_NONE,
        0x0
    },
    {
      wxCMD_LINE_SWITCH,
        _T(""),
        _T("no_interface"),
        gettext_noop("start game with user interface hidden"),
        wxCMD_LINE_VAL_NONE,
        0x0
    },
    {
      wxCMD_LINE_SWITCH,
        _T(""),
        OPTION_PAWN_DEBUG,
        gettext_noop("start game with source level script debugging"),
        wxCMD_LINE_VAL_NONE,
        0x0
    },

    {
      wxCMD_LINE_SWITCH,
        _T(""),
        OPTION_NO_ART_CHECK,
        gettext_noop("Don't check source art"),
        wxCMD_LINE_VAL_NONE,
        0x0
    },
    {
      wxCMD_LINE_OPTION,
      _T(""),
      OPTION_PLAYER_MODEL,
      gettext_noop("name of .esf to use for the player"),
      wxCMD_LINE_VAL_STRING,
      0x0
    },
    // terminator
    {
      wxCMD_LINE_NONE,
      _T(""),
      _T(""),
      _T(""),
      wxCMD_LINE_VAL_NONE,
      0x0
    }
  };

  parser.SetDesc(cmdLineDesc);
}

// called after successfully parsing the command line, return true
// to continue and false to exit (don't forget to call the base class
// version if you override it!)
bool TitanApp::OnCmdLineParsed(wxCmdLineParser& parser)
{
  wxString videoMode;
  if ( parser.Found(OPTION_VIDEO, &videoMode ))
  {
    const wxChar *mode = videoMode.GetData();
    SyInitVideoMode(mode);
  }
  else
  {
    SyInitVideoMode(NULL);      // init to whatever default it wants to
  }

  if ( parser.Found(OPTION_NET) )
  {
    mNet = true;
  }

  if ( parser.Found(OPTION_MULTIPASS) )
  {
    mMultiPass = true;
  }

  if ( parser.Found(OPTION_BLOOM) )
  {
    mBloomEnabled = true;
  }

  if ( parser.Found(OPTION_PS2) )
  {
    mpTitanFrame->mpTitanUI->SetControllerMapping(TitanUI::CONTROLLER_MAPPING_PS2);
  }

  if ( parser.Found(OPTION_LOGITECH) )
  {
    mpTitanFrame->mpTitanUI->SetControllerMapping(TitanUI::CONTROLLER_MAPPING_LOGITECH);
    SySetButtonMapping( 0, "logitech" );
  }

  if ( parser.Found(OPTION_LOG) )
  {
    mLog = true;
  }

  wxString levelname;
  if ( parser.Found(OPTION_LEVEL,&levelname ))
  {
    if (levelname.GetData()[0] != '\0')
    {
      delete mLevelName;
      mLevelName = strdup(levelname.GetData());
    }
  }

  wxString moviename;
  if ( parser.Found(OPTION_MOVIE, &moviename ))
  {
    const wxChar *filename = moviename.GetData();
    SyInitMovieMode(filename);
  }

  wxString playbackName;
  if ( parser.Found(OPTION_PLAYBACK,&playbackName ))
  {
    const wxChar *filename = playbackName.GetData();
    if (filename[0] == 0)
        filename = _T("titan.dem");

    strcpy(mPlaybackFilename, filename);
    SyInitPlaybackMode(filename);
  }
  else  // no record command line check if playback is specified
  {
    wxString recordName;
    if ( parser.Found(OPTION_RECORD,&recordName ))
    {
        const wxChar *filename = recordName.GetData();
        if (filename[0] == 0)
            filename = _T("titan.dem");

        strcpy(mRecordFilename, filename);
        SyInitRecordMode(filename);
    }
  }

  if ( parser.Found(OPTION_NO_INTERFACE) )
  {
    mShowUI = false;
  }

  long rate;
  if ( parser.Found(OPTION_FRAMERATE, &rate ))
  {
    SyInitFixedFrameMode((int)rate);
  }

  if ( parser.Found(OPTION_PAWN_DEBUG) )
  {
    mPawnDebug = true; 
  }

  if ( parser.Found(OPTION_NO_ART_CHECK) )
  {
    mArtCheck = false; 
  }

  wxString modelname;
  if ( parser.Found(OPTION_PLAYER_MODEL,&modelname ))
  {
    if (modelname.GetData()[0] != '\0')
    {
      delete mPlayerModelOverload;

      static const char *path = "data/art/character/";
      static const char *extension = ".esf";
      mPlayerModelOverload = new char[strlen(modelname.GetData())+strlen(path)+strlen(extension)+ 1]; 
      sprintf(mPlayerModelOverload,"%s%s%s",path,modelname.GetData(),extension);
    }
  }

  return wxApp::OnCmdLineParsed(parser);
}


