// $Id: batchconverter.cpp,v 1.23 2018/01/03 21:32:58 mkkuhner Exp $

/*
Copyright 2002-2005 Mary K. Kuhner, Peter Beerli, and Joseph Felsenstein

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

/* Authors: Mary Kuhner, Jon Yamato, and Joseph Felsenstein */


#include "batchconverter.h"
#include "gc_cmdline.h"
#include "gc_data.h"
#include "gc_datastore.h"
#include "gc_errhandling.h"
#include "gc_strings.h"
#include "tinyxml.h"
#include "wx/cmdline.h"

BatchConverterApp::BatchConverterApp()
    : GCCmdLineManager()
{
}

BatchConverterApp::~BatchConverterApp()
{
}

IMPLEMENT_APP(BatchConverterApp)

void
BatchConverterApp::OnInitCmdLine(wxCmdLineParser& parser)
{
    wxAppConsole::OnInitCmdLine(parser);
    GCCmdLineManager::AddOptions(parser);
}

bool
BatchConverterApp::OnCmdLineParsed(wxCmdLineParser& parser)
{
    bool parentReturned = wxAppConsole::OnCmdLineParsed(parser);
    GCCmdLineManager::ExtractValues(parser);
    return parentReturned;
}

bool
BatchConverterApp::OnInit()
{
    return wxAppConsole::OnInit();
}

int
BatchConverterApp::OnRun()
{
    try
    {
        // EWFIX.P4 LATER -- break up command line and command file processing
        int exitCode = GCCmdLineManager::ProcessCommandLineAndCommandFile(m_dataStore);
        if(exitCode == 0)
        {
            exitCode = GCCmdLineManager::DoExport(m_dataStore);
        }
        if(exitCode == 0)
        {
            wxLogMessage(gcstr::batchSafeFinish);
        }
        return exitCode;
    }
    catch(const gc_fatal_error& e)
    {
        wxLogError(wxString::Format(gcerr::fatalError));
        return 2;
    }
    catch(const std::exception& f)
    {
        wxLogError(wxString::Format(gcerr::uncaughtException,f.what()));
        return 2;
    }

    return 3;       // EWFIX.P3 -- what should this be?
}

int
BatchConverterApp::OnExit()
{
    if(m_doDebugDump)
    {
        m_dataStore.DebugDump();
    }
    if(! m_batchOutName.IsEmpty())
    {
        TiXmlDocument * doc = m_dataStore.ExportBatch();
        m_dataStore.WriteBatchFile(doc,m_batchOutName);
        delete doc;
    }

    m_dataStore.NukeContents();
    return wxAppConsole::OnExit();
}

//____________________________________________________________________________________
