/*

  xmunipack - main

  Copyright © 2009-2015, 2019-20 F.Hroch (hroch@physics.muni.cz)

  This file is part of Munipack.

  Munipack is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  Munipack is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with Munipack.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "xmunipack.h"
#include <wx/wx.h>
#include <wx/app.h>
#include <wx/cmdline.h>
#include <wx/debugrpt.h>
#include <wx/protocol/ftp.h>
#include <wx/wfstream.h>
#include <cstdlib>

#define FTP_LOGIN     "wxDebugReport"
#define FTP_PASSWORD  "wxDebugReport"
#define FTP_SERVER    "integral.physics.muni.cz"


wxIMPLEMENT_APP(XMunipack);

bool XMunipack::OnInit()
{
  config = 0;
  view = 0;
  browser = 0;

  // switch-off timestamps in log
  wxLog::DisableTimestamp();

  // default log level prints errors only
  wxLog::SetLogLevel(wxLOG_Error);

  // command line parameters
  wxCmdLineParser cmd(argc,argv);
  OnInitCmdLine(cmd);
  cmd.AddSwitch("","version","print version and license");
  cmd.AddParam("filename",wxCMD_LINE_VAL_STRING,wxCMD_LINE_PARAM_OPTIONAL);

  if( cmd.Parse() == 0 ) {

    if( cmd.Found("verbose") )
      wxLog::SetLogLevel(wxLOG_Debug);

    if( cmd.Found("version") ) {
      wxPrintf("%s %s, %s\n",PACKAGE_NAME,PACKAGE_VERSION,PACKAGE_COPYLEFT);
      wxPrintf("%s\n\n",PACKAGE_DESCRIPTION);
      wxPrintf("This program comes with ABSOLUTELY NO WARRANTY;\nfor details, see the GNU General Public License, version 3 or later.\n");
      return false;
    }

  }
  else
    return false;

  // look for passed file
  wxString file;
  if( cmd.GetParamCount() > 0 )
    file = cmd.GetParam();


  // initialisation
  wxHandleFatalExceptions();
  wxInitAllImageHandlers();
  config = new MuniConfig();

#ifdef __WXMAC__
  // all main windows?
  SetExitOnFrameDelete(true);
  wxMenuBar *menubar = new wxMenuBar;
  wxMenuBar::MacSetCommonMenuBar(menubar);
#endif


  if( ! file.IsEmpty() ) {

    view = new MuniView(NULL,config);
    view->Show();
    view->LoadFile(file);
    SetTopWindow(view);
  }
  else {

    browser = new MuniBrowser(NULL,config);
    browser->Show(true);

  }

  return true;
}


int XMunipack::OnExit()
{
  delete config;
  return 0;
}


void XMunipack::OnFatalException()
{
  wxDebugReport report;
  wxDebugReportPreviewStd preview;

  report.AddAll();

  if ( preview.Show(report) ) {

    // upload the report to home ftp
    for(size_t i = 0; i < report.GetFilesCount(); i++) {
      wxString name, desc;
      report.GetFile(i,&name,&desc);
      wxFileName file(report.GetDirectory(),name);

      wxFTP ftp;
      ftp.SetUser(FTP_LOGIN);
      ftp.SetPassword(FTP_PASSWORD);

      if ( !ftp.Connect(FTP_SERVER) ) {
        wxLogError("Couldn't send bug report: Failed to connect.\n"
		   "Leaving files in "+report.GetDirectory()+".\n");
	report.Reset();
        return;
      }

      wxDateTime dt(wxDateTime::Now());
      dt.MakeUTC();
      wxString oname(dt.Format("%Y-%m-%d_%H:%M:%S_")+name);
      wxOutputStream *out = ftp.GetOutputStream(oname);
      wxFileInputStream in(file.GetFullPath());
      wxASSERT(in.IsOk() && out && out->IsOk());
      if( out ) {
	out->Write(in);
	delete out;
      }

    }

  }
}

void XMunipack::OnEventLoopEnter(wxEventLoopBase* WXUNUSED(loop))
{
  //  wxLogDebug("XMunipack::OnEventLoopEnter");
  if( view )
    view->CreateFSWatch();
}
