/////////////////////////////////////////////////////////////////////////////
// Name:        dvdstyler.cpp
// Purpose:     DVD Authoring Application
// Author:      Alex Thuering
// Created:	10.10.2003
// RCS-ID:      $Id: dvdstyler.cpp,v 1.42 2010/02/22 22:47:18 ntalex Exp $
// Copyright:   (c) Alex Thuering
// Licence:     GPL
/////////////////////////////////////////////////////////////////////////////

#include "WelcomeDlg.h"
#include "TemplateDlg.h"
#include "MainWin.h"
#include "About.h"
#include "Config.h"
#include "Languages.h"
#include "MPEG.h"
#include <wx/config.h>
#include <wx/filesys.h>
#include <wx/fs_zip.h>
#include <wxVillaLib/imagjpg.h>
#include <wxVillaLib/utils.h>
#include <wxVillaLib/ThumbnailFactory.h>
#include <wxSVG/SVGCanvas.h>
#include <wxSVG/mediadec_ffmpeg.h>
#include <wx/cmdline.h>

#ifndef __WXWINCE__
#include <locale.h>
#endif

#include "rc/dvdstyler.png.h"

#define LOCALE_DIR wxFindDataDirectory(_T("..") + wxString(wxFILE_SEP_PATH) + _T("locale"))

class DVDStyler : public wxApp {
public:
	bool OnInit();

protected:
	wxLocale m_locale;
};

IMPLEMENT_APP(DVDStyler)

bool DVDStyler::OnInit() {
	// fix config
	s_config.Init();
	wxString version = s_config.GetVersion();
	if (version.length() < 3 || version.Mid(0, 3) != APP_VERSION.Mid(0, 3)) {
		wxLogNull log;
		s_config.SetVersion(APP_VERSION);
		if (version.length() >= 3 && version.Mid(0, 3) == wxT("1.5")) {
			s_config.DeleteGroup(_T("Generate"));
		} else if (version.Mid(0, 3) != wxT("1.7")) {
			s_config.DeleteGroup(_T("Generate"));
			s_config.DeleteGroup(_T("Preview"));
			s_config.DeleteGroup(_T("Iso"));
			s_config.DeleteGroup(_T("Burn"));
		}
		s_config.Flush();
	} else if (version != APP_VERSION)
		s_config.SetVersion(APP_VERSION);

	wxInitAllImageHandlers();
	// load new jpeg handler (with scale option)
	if (!wxImage::RemoveHandler(_T("JPEG file")))
		wxMessageBox(_T("Error: Can't remove old JPEG handler"));
	wxImage::InsertHandler(new wxJPGHandler);
	
    wxFileSystem::AddHandler(new wxZipFSHandler);

	wxThumbnailFactory::InitGnome(APP_NAME.mb_str(), APP_VERSION.mb_str(), argc, (char**)argv);

	// locale
	int lang = s_config.GetLanguage();
	bool firstStart = lang == wxLANGUAGE_UNKNOWN;
	if (firstStart) {
		wxString languageCode = s_config.GetLanguageCdoe();
		if (languageCode.length() > 0 && wxLocale::FindLanguageInfo(languageCode)) {
			lang = wxLocale::FindLanguageInfo(languageCode)->Language;
		} else
			lang = ChooseLanguage();
		wxString langStr = wxLocale::GetLanguageInfo(lang)->CanonicalName;
		if (langStr.length() > 2)
			langStr = langStr.substr(0, 2);
		if (DVD::GetAudioLanguageCodes().Index(langStr.Upper()) != wxNOT_FOUND)
			s_config.SetDefAudioLanguage(langStr.Upper());
	}
	if (lang != wxLANGUAGE_ENGLISH) {
		m_locale.Init(lang);
		m_locale.AddCatalogLookupPathPrefix(LOCALE_DIR);
		m_locale.AddCatalog(wxT("dvdstyler"));
	}

#ifndef __WXWINCE__
	setlocale(LC_NUMERIC, "C");
#endif

	wxFfmpegMediaDecoder::Init();
#ifndef __WXMSW__
	if (firstStart) {
		// check if mplex exists
		wxLogNull log;
		bool mplex = wxExecute(wxT("mplex"), wxEXEC_SYNC | wxEXEC_NODISABLE) == 1;
		s_config.SetUseMplex(mplex);
	}
#endif
	
	// create main window
	MainWin* mainWin = new MainWin();
#ifndef __WXMSW__
	mainWin->SetIcon(wxICON_FROM_MEMORY(dvdstyler));
#else
	mainWin->SetIcon(wxICON(dvdstyler));
#endif
	
	// parse command line
	static const wxCmdLineEntryDesc cmdLineDesc[] = {
		{ wxCMD_LINE_SWITCH, wxString(wxT("s")), wxString(wxT("start")), _("automatically starts the generation and burning") },
		{ wxCMD_LINE_SWITCH, wxString(wxT("e")), wxString(wxT("stderr")), _("write log messages to standard error") },
		{ wxCMD_LINE_SWITCH, wxString(wxT("v")), wxString(wxT("version")), _("show version of program") },
		{ wxCMD_LINE_SWITCH, wxString(wxT("h")), wxString(wxT("help")), _("show summary of options") },
		{ wxCMD_LINE_PARAM, NULL, NULL, _("input file"), wxCMD_LINE_VAL_STRING,
				wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE },
		{ wxCMD_LINE_NONE }
	};
	
	wxCmdLineParser parser(cmdLineDesc, argc, argv);
	wxString logoText= wxT("DVDStyler, version ") + APP_VERSION
			+ wxString("\nCopyright © 2008 Alex Thüring. All Rights Reserved.\n", wxConvISO8859_1);
	parser.SetLogo(logoText);
	if (parser.Parse() != 0) {
		exit(1);
	} else if (parser.Found(wxT("v"))) {
		fprintf(stdout, "%s", (const char*) logoText.mb_str());
		exit(0);
	} else if (parser.Found(wxT("h"))) {
		parser.Usage();
		exit(0);
	}
	
	if (parser.Found(wxT("e"))) {
		wxLog::SetActiveTarget(new wxLogStderr);
		wxLog::GetActiveTarget()->SetVerbose(true);
	}
	
	for (int i=0; i<(int)parser.GetParamCount(); i++) {
		wxString filename = parser.GetParam(i);
		if (i == 0 && (filename.Lower().EndsWith(wxT(".xml")) || filename.Lower().EndsWith(wxT(".dvds")))) { 
			mainWin->Open(filename);
		} else {
			wxFfmpegMediaDecoder decoder;
			if (decoder.Load(filename))
				mainWin->AddTitle(filename);
		}
	}
	
	// show main window
	mainWin->Show();
	SetTopWindow(mainWin);
	if (parser.Found(wxT("s")))
		mainWin->Burn(true);
	
	if (parser.GetParamCount() == 0 && s_config.GetShowWelcomeDlg()) {
		// show welcome dialog
		WelcomeDlg dlg(mainWin);
		if (dlg.ShowModal() == wxID_OK) {
			if (dlg.IsNewProject()) {
				TemplateDlg templateDlg(mainWin);
				wxString templateFile = templateDlg.ShowModal() == wxID_OK ? templateDlg.GetTemplate() : wxT("");
				mainWin->NewDVD(templateFile, templateDlg.GetTitle(), dlg.GetLabel(), dlg.GetCapacity(),
						dlg.GetVideoBitrate(), dlg.GetVideoFormat(), dlg.GetAudioFormat(), dlg.GetAspectRatio());
			} else if (dlg.GetOpenFilename().length() > 0) {
				mainWin->Open(dlg.GetOpenFilename());
			} else {
				mainWin->ShowOpenDlg();
			}
		}
	}
	
	s_config.SetLanguage(lang); // save choosed languages if all ok
	return true;
}
