/////////////////////////////////////////////////////////////////////////////
// Name:        mainfrm.cpp
// Purpose:     wx Package Manager main app class
// Author:      Julian Smart, Francesco Montorsi
// Modified by:
// Created:     2004-11-08
// RCS-ID:      $Id: mainfrm.cpp,v 1.6 2007/02/02 08:48:51 frm Exp $
// Copyright:   (c) Julian Smart
// Licence:     wxWidgets licence
/////////////////////////////////////////////////////////////////////////////


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

#ifdef __BORLANDC__
#pragma hdrstop
#endif

#include <wx/notebook.h>
#include <wx/menu.h>
#include <wx/sizer.h>
#include <wx/msgdlg.h>
#include <wx/splitter.h>
#include <wx/filedlg.h>
#include <wx/intl.h>
#include <wx/dirdlg.h>
#include <wx/filesys.h>
#include <wx/html/helpctrl.h>
#include <wx/settings.h>
#include <wx/aboutdlg.h>

#include "symbols.h"
#include "mainfrm.h"
#include "app.h"

#include "guipm/browsepanel.h"
#include "guipm/viewerpanel.h"
//#include "guipm/proppanel.h"
//#include "guipm/newwizard.h"
#include "guipm/settingsdlg.h"

#include "wxp/wxp.h"



// define to 1 to get a wxPM without browser and viewer panels !
#define wxTEST      0


// ----------------------------------------------------------------------------
// XPM resources
// ----------------------------------------------------------------------------

#include "bitmaps/wxpm16x16.xpm"
#include "bitmaps/wxpm32x32.xpm"



// ----------------------------------------------------------------------------
// wxPackageManagerFrame
// ----------------------------------------------------------------------------

enum wxPackageManagerFrameID
{
    ID_FRAME_OPENPKG,
    ID_FRAME_SETTINGS,

    ID_FRAME_DOWNLOAD,
    ID_FRAME_DECOMPRESS,
    ID_FRAME_BUILD,
    ID_FRAME_INSTALL,
    ID_FRAME_UNINSTALL,
};

IMPLEMENT_CLASS(wxPackageManagerFrame, wxFrame)
BEGIN_EVENT_TABLE(wxPackageManagerFrame, wxFrame)
    EVT_CLOSE(wxPackageManagerFrame::OnCloseWindow)

    // file
    EVT_MENU(wxID_OPEN, wxPackageManagerFrame::OnOpenPackage)
    EVT_MENU(wxID_PREFERENCES, wxPackageManagerFrame::OnSettings)
    EVT_MENU_RANGE(wxID_FILE1, wxID_FILE9, wxPackageManagerFrame::OnMRUFile)

    // help
    EVT_MENU(wxID_ABOUT, wxPackageManagerFrame::OnAbout)
    EVT_MENU(wxID_HELP, wxPackageManagerFrame::OnHelp)

    EVT_MENU(wxID_EXIT, wxPackageManagerFrame::OnExit)
END_EVENT_TABLE()


bool wxPackageManagerFrame::Create()
{
    int defw = (int)(wxSystemSettings::GetMetric(wxSYS_SCREEN_X)*0.8),
        defh = (int)(wxSystemSettings::GetMetric(wxSYS_SCREEN_Y)*0.8);

    // create the frame directly with loaded size & position
    wxPoint pos = wxDefaultPosition;
    wxSize sz = wxDefaultSize;
    wxConfigBase::Get()->Read(_T("Windows/MainWindowX"), &pos.x, 50);
    wxConfigBase::Get()->Read(_T("Windows/MainWindowY"), &pos.y, 50);
    wxConfigBase::Get()->Read(_T("Windows/MainWindowWidth"), &sz.x, defw);
    wxConfigBase::Get()->Read(_T("Windows/MainWindowHeight"), &sz.y, defh);

    if (sz.x > defw) sz.x = defw;
    if (sz.y > defh) sz.y = defh;

    if (!wxFrame::Create(NULL, wxID_ANY, wxT("wxWidgets Package Manager"), pos, sz))
    {
        wxLogError(wxT("Could not create the wxPackageManagerFrame!"));
        return false;
    }

    // load most recently used (MRU) file list
    m_mru.Load(*wxConfigBase::Get());

    // set icons
    wxIconBundle iconBundle;
    iconBundle.AddIcon(wxIcon(wxpm16x16_xpm));
    iconBundle.AddIcon(wxIcon(wxpm32x32_xpm));
    SetIcons(iconBundle);

    // create menu bar
    wxMenuBar* menuBar = new wxMenuBar;
    wxMenu* fileMenu = new wxMenu;
    wxMenu* packageMenu = new wxMenu;
    wxMenu* helpMenu = new wxMenu;

    // file menu
    fileMenu->Append(wxID_OPEN, wxT("Open local package..."));
    fileMenu->AppendSeparator();
    fileMenu->Append(wxID_PREFERENCES, wxT("Settings..."));
    fileMenu->AppendSeparator();
    fileMenu->Append(wxID_EXIT);
    //fileMenu->AppendSeparator();
    //m_mru.AddFilesToMenu(fileMenu);

    // package menu
    packageMenu->Append(ID_BROWSER_DOWNLOAD, wxT("Download..."));
    packageMenu->Append(ID_BROWSER_DECOMPRESS, wxT("Decompress..."));
    packageMenu->Append(ID_BROWSER_REBUILD, wxT("(Re)Build..."));
    packageMenu->Append(ID_BROWSER_REINSTALL, wxT("(Re)Install..."));
    packageMenu->Append(ID_BROWSER_UNINSTALL, wxT("Uninstall..."));

    // help menu
    helpMenu->Append(wxID_HELP, wxT("Packager Guide"));
    helpMenu->Append(wxID_ABOUT);

    menuBar->Append(fileMenu, wxT("&File"));
    menuBar->Append(packageMenu, wxT("&Package"));
    menuBar->Append(helpMenu, wxT("&Help"));
    SetMenuBar(menuBar);

    // create child windows
    CreateStatusBar(1);
    SetStatusText(wxT("Welcome to the wxWidgets package manager!"));


#if !wxTEST
    wxSplitterWindow *splitter = new wxSplitterWindow(this, wxID_ANY);
    m_browser = new wxPackageBrowserPanel(splitter);
    m_viewer = new wxPackageViewerPanel(splitter);

    // init the browser panel:
    m_browser->SetAuxiliaryViewerPanel(m_viewer);
    m_browser->SetAuxiliaryMenuBar(menuBar);
    m_browser->SetAuxiliaryStatusBar(GetStatusBar());

    wxPackageBrowserPanel::s_strDefaultWxlName = DEFAULT_WXL_FILENAME;
    wxPackageBrowserPanel::s_strDefaultWxlURL = DEFAULT_REPO_URL;

    splitter->SplitVertically(m_browser, m_viewer, 100);

    if (!m_viewer->LoadViewFormats())
        return false;

    if (!IsOk())
        return false;

    // load panel settings
    m_viewer->Load(wxConfigBase::Get(), wxEmptyString);
    m_browser->Load(wxConfigBase::Get(), wxEmptyString);

    // set the min size of this frame
    // NB: the +10 is just for max security; the +50 is because there's
    //     the menubar+statusbar to take in count
    // NB2: there's probably a better way to solve this !
    wxSize sz1(m_browser->GetMinSize()), sz2(m_viewer->GetMinSize());
    SetMinSize(wxSize(sz1.GetWidth()+sz2.GetWidth()+10,
                      wxMax(sz1.GetHeight()+30, sz2.GetHeight()+30)));
#endif

    return true;
}

wxPackageManagerFrame::~wxPackageManagerFrame()
{
#if !wxTEST
    if (IsOk())
    {
        // save settings
        m_viewer->Save(wxConfigBase::Get(), wxEmptyString);
        m_browser->Save(wxConfigBase::Get(), wxEmptyString);
    }
#endif
}

bool wxPackageManagerFrame::IsOk() const
{
    return m_viewer!=NULL && m_browser!=NULL &&
           m_viewer->IsOk();
}

void wxPackageManagerFrame::Open(const wxString &filename)
{
    if (!m_browser->LoadCompressedPackage(filename))
    {
        wxLogError(_("Cannot load the '%s' package.\n\nIt's invalid or it's already listed."),
                    filename.c_str());
    }

    wxMessageBox(wxT("Not working yet - sorry."));
    //m_browser->BrowseTo(path);
    //m_browser->SelectNewPackage(wxT("wxrc"));
/*
    // find the package whose WXP is called dlg.GetFileName()
    wxPackageArray arr(m_browser->GetNewPackages());
    for (size_t i=0; i<arr.GetCount(); i++)
        if (arr[i].Get
            m_browser->SelectNewPackage(i);
*/
}



// ----------------------------------------------------------------------------
// wxPackageManagerFrame - event handlers
// ----------------------------------------------------------------------------

void wxPackageManagerFrame::OnOpenPackage(wxCommandEvent&)
{
    wxFileDialog dlg(this, wxT("Choose the package to open"),
                    wxEmptyString, wxT(""),
                    wxT("Compressed wxWidgets packages (*.wxz,*.tar.gz,*.zip)|*.wxz,*.tar.gz,*.zip"),
                    wxFD_OPEN|wxFD_FILE_MUST_EXIST);

    dlg.CentreOnParent();
    if (dlg.ShowModal() == wxID_OK)
    {
        wxFileName f(dlg.GetPath());
        Open(f.GetFullPath());
    }
}

void wxPackageManagerFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
{
    wxAboutDialogInfo info;
    info.SetName(_("wxWidgets Package Manager"));
    info.SetDescription(
        wxT("A useful tool for managing build, install and uninstall\n")
        wxT("stages of wxWidgets-based software.\n\n")
        wxT("Project kindly sponsored by Google and mentored by Julian Smart."));
    info.SetIcon(this->GetIcon());

    SetGlobalAboutInfo(info);
    wxAboutBox(info);
}

void wxPackageManagerFrame::OnCloseWindow(wxCloseEvent& WXUNUSED(event))
{
    if (!IsIconized())
    {
        wxSize sz = GetSize();
        wxPoint pos = GetPosition();

        wxConfigBase::Get()->Write(_T("/Windows/MainWindowX"), pos.x);
        wxConfigBase::Get()->Write(_T("/Windows/MainWindowY"), pos.y);
        wxConfigBase::Get()->Write(_T("/Windows/MainWindowWidth"), sz.x);
        wxConfigBase::Get()->Write(_T("/Windows/MainWindowHeight"), sz.y);
    }

    Destroy();
}

void wxPackageManagerFrame::OnExit(wxCommandEvent& WXUNUSED(event))
{
    // the following will call automatically OnCloseWindow
    Close(true);
}

void wxPackageManagerFrame::OnHelp(wxCommandEvent& WXUNUSED(event))
{
    m_viewer->SelectReferencePage();

    // FIXME: pm.htb is just a copy of wx.htb ATM !!
    m_viewer->GetEmbeddedHelpController()->Display(wxT("The wxWidgets Package Manager"));
}

void wxPackageManagerFrame::OnMRUFile(wxCommandEvent& event)
{
    wxString f(m_mru.GetHistoryFile(event.GetId() - wxID_FILE1));
    //if (!f.empty())
        //m_browser->BrowseTo(f);
}

void wxPackageManagerFrame::OnSettings(wxCommandEvent& WXUNUSED(event))
{
    wxPackageManagerSettingsDlg dlg(this, -1,
            wxConfigBase::Get(), wxT("/"),
            m_viewer, m_browser);

    dlg.LoadSettings();
    if (dlg.ShowModal() == wxID_OK)
        dlg.ApplySettings();
}
