/////////////////////////////////////////////////////////////////////////////
// Name:        viewerpanel.cpp
// Purpose:     wxPackageViewerPanel
// Author:      Julian Smart, Francesco Montorsi
// Modified by:
// Created:     04/06/2006 15:41:31
// RCS-ID:      $Id: viewerpanel.cpp,v 1.4 2007/02/01 11:56:54 frm Exp $
// Copyright:   (c) 2004 Francesco Montorsi
// Licence:     wxWidgets license
/////////////////////////////////////////////////////////////////////////////


// 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

#include "wx/tokenzr.h"
#include "wx/stdpaths.h"
#include "wx/ffile.h"

#include "guipm/viewerpanel.h"
#include "wxp/package.h"
#include "wx/webbrowser.h"

#ifdef __WXMSW__
    #include "wx/msw/helpchm.h"
    #include "wx/msw/private.h"
    #include "wx/msw/uxtheme.h"
#else
    #include "wx/html/helpctrl.h"
#endif

#include "wx/html/helpwnd.h"
#include "wx/html/helpctrl.h"
#include "wx/html/helpfrm.h"


// ----------------------------------------------------------------------------
// wxPackageViewerPanel
// ----------------------------------------------------------------------------

IMPLEMENT_DYNAMIC_CLASS( wxPackageViewerPanel, wxPanel )
BEGIN_EVENT_TABLE( wxPackageViewerPanel, wxPanel )

    // NB: the ID of the html windows are important to avoid intercepting
    //     the link events for the wxHtmlHelpWindow!
    EVT_HTML_LINK_CLICKED(ID_VIEWER_SUMMARY, wxPackageViewerPanel::OnLinkClicked)
    EVT_HTML_LINK_CLICKED(ID_VIEWER_DETAILS, wxPackageViewerPanel::OnLinkClicked)

    EVT_NOTEBOOK_PAGE_CHANGED(ID_VIEWER_NOTEBOOK, wxPackageViewerPanel::OnPageChanged)
END_EVENT_TABLE()

wxPackageViewerPanel::wxPackageViewerPanel( )
{
}

wxPackageViewerPanel::wxPackageViewerPanel( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style )
{
    Create(parent, id, pos, size, style);
}

wxPackageViewerPanel::~wxPackageViewerPanel()
{
    if (m_embeddedHelpController)
    {
        m_embeddedHelpController->SetHelpWindow(NULL);
        wxDELETE(m_embeddedHelpController);
    }
}

bool wxPackageViewerPanel::Create( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style )
{
////@begin wxPackageViewerPanel member initialisation
    m_pNotebook = NULL;
    m_pSummaryHtmlWin = NULL;
    m_pDetailsHtmlWin = NULL;
////@end wxPackageViewerPanel member initialisation
    m_embeddedHelpWindow = NULL;
    m_embeddedHelpController = NULL;

////@begin wxPackageViewerPanel creation
    SetExtraStyle(GetExtraStyle()|wxWS_EX_BLOCK_EVENTS);
    wxPanel::Create( parent, id, pos, size, style );

    CreateControls();
    if (GetSizer())
    {
        GetSizer()->SetSizeHints(this);
    }
    Centre();
////@end wxPackageViewerPanel creation

    return true;
}

bool wxPackageViewerPanel::IsOk() const
{
    if (!m_viewMode.IsOk())
        return false;
    return true;
}

void wxPackageViewerPanel::CreateControls()
{
////@begin wxPackageViewerPanel content construction
    wxPackageViewerPanel* itemPanel1 = this;

    wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL);
    itemPanel1->SetSizer(itemBoxSizer2);

    m_pNotebook = new wxNotebook( itemPanel1, ID_VIEWER_NOTEBOOK, wxDefaultPosition, wxDefaultSize, wxNB_TOP );

    wxPanel* itemPanel4 = new wxPanel( m_pNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
    wxBoxSizer* itemBoxSizer5 = new wxBoxSizer(wxVERTICAL);
    itemPanel4->SetSizer(itemBoxSizer5);

    m_pSummaryHtmlWin = new wxHtmlWindow( itemPanel4, ID_VIEWER_SUMMARY, wxDefaultPosition, wxSize(200, 150), wxHW_SCROLLBAR_AUTO|wxSUNKEN_BORDER|wxHSCROLL|wxVSCROLL );
    itemBoxSizer5->Add(m_pSummaryHtmlWin, 1, wxGROW|wxALL, 5);

    m_pNotebook->AddPage(itemPanel4, _("Summary"));

    wxPanel* itemPanel7 = new wxPanel( m_pNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
    wxBoxSizer* itemBoxSizer8 = new wxBoxSizer(wxVERTICAL);
    itemPanel7->SetSizer(itemBoxSizer8);

    m_pDetailsHtmlWin = new wxHtmlWindow( itemPanel7, ID_VIEWER_DETAILS, wxDefaultPosition, wxSize(200, 150), wxHW_SCROLLBAR_AUTO|wxSUNKEN_BORDER|wxHSCROLL|wxVSCROLL );
    itemBoxSizer8->Add(m_pDetailsHtmlWin, 1, wxGROW|wxALL, 5);

    m_pNotebook->AddPage(itemPanel7, _("Details"));

    itemBoxSizer2->Add(m_pNotebook, 1, wxGROW, 5);

////@end wxPackageViewerPanel content construction


    // Create reference tab
    m_embeddedHelpController = new wxHtmlHelpController;
    m_embeddedHelpWindow = new wxHtmlHelpWindow;
    m_embeddedHelpWindow->SetController(m_embeddedHelpController);
    m_embeddedHelpController->SetHelpWindow(m_embeddedHelpWindow);
    m_embeddedHelpWindow->Create(m_pNotebook, wxID_ANY, wxDefaultPosition,
                                wxSize(200, 100), wxTAB_TRAVERSAL|wxNO_BORDER,
                                wxHF_DEFAULT_STYLE);
    m_pNotebook->AddPage(m_embeddedHelpWindow, _("Documentation"), FALSE);

#ifdef __WXMSW__
    if (wxUxThemeEngine::Get()->IsThemeActive())
    {
        wxColour backColour = m_pNotebook->GetThemeBackgroundColour();
        if (m_embeddedHelpWindow->GetToolBar())
            m_embeddedHelpWindow->GetToolBar()->SetBackgroundColour(backColour);
    }
#endif

    // Create the download tab
    m_pDownloadQueuePanel = new wxPackageDownloadQueuePanel(m_pNotebook, wxID_ANY);
    m_pNotebook->AddPage(m_pDownloadQueuePanel, _("Downloads"), FALSE);

    // Create the build tab
    m_pTaskQueuePanel = new wxPackageCommandQueuePanel(m_pNotebook, wxID_ANY);
    m_pNotebook->AddPage(m_pTaskQueuePanel, _("Builds"), FALSE);

    // Create the web browser
#if wxPM_HAS_EMBEDDED_BROWSER
    wxWebBrowserWindow* webBrowserWindow = new wxWebBrowserWindow(m_pNotebook, wxID_ANY);
    webBrowserWindow->CreateWindows();
    m_pNotebook->AddPage(webBrowserWindow, _("Browser"), FALSE);
#endif

    // init the html windows
#ifdef __WXMSW__
    m_pSummaryHtmlWin->SetFonts(wxT("Trebuchet MS"), wxEmptyString, NULL);
#endif
    Reset();
}

bool wxPackageViewerPanel::ShowToolTips()
{
    return true;
}

bool wxPackageViewerPanel::LoadViewFormats()
{
    m_viewMode = wxPackageInfo::s_hashmapHTMLFormats[wxT("simple")];

    // load view formats
    wxPackageHTMLOutputFormat temp;
    if (!temp.Load(wxStandardPaths::Get().GetDataDir() +
         wxFileName::GetPathSeparator() + 
         wxT("defaultpages")))
        return false;

    m_strDefaultSummary = temp.GetSummary();
    m_strDefaultDetails = temp.GetDetails();

    return true;
}


// ----------------------------------------------------------------------------
// wxPackageViewerPanel - additional functions
// ----------------------------------------------------------------------------

void wxPackageViewerPanel::InitReference()
{
    for (size_t i=0; i<m_arrDocs.GetCount(); i++)
    {
        wxString f = m_arrDocs[i];
        if (!wxIsAbsolutePath(f))
        {
            wxString sep(wxFileName::GetPathSeparator());
            wxFileName fn(wxStandardPaths::Get().GetDataDir() + sep +
                        wxT("docs") + sep + f);
            fn.Normalize(wxPATH_NORM_DOTS|wxPATH_NORM_ABSOLUTE);
            f = fn.GetFullPath();
        }
        GetEmbeddedHelpController()->AddBook(wxFileName(f), true);
    }
}

void wxPackageViewerPanel::UpdateSummaryAndDesc()
{
    wxString summary, details;

    if (m_arrPkg.GetCount() == 0)
    {
        // just set default msg
        Reset();
        return;
    }
    else if (m_arrPkg.GetCount() == 1)
    {
        summary = m_viewMode.GetSummaryFor(m_arrPkg[0]);
        details = m_viewMode.GetDetailsFor(m_arrPkg[0]);
        summary = wxT("<html><body>") + summary + wxT("</body></html>");
    }
    else
    {
        summary = wxT("<html><body><div align='center'>")
        wxT("<h2><u>Summary of selected packages</u></h2>")
        wxT("</div>");

        for (size_t i=0; i<m_arrPkg.GetCount(); i++)
        {
                // FIXME - need some way to make this list nicer
                /*summary += wxString::Format(wxT("<b>%s</b><br>"),
                                m_arrPkg[i].GetName().c_str());*/
            summary += m_viewMode.GetSummaryFor(m_arrPkg[i]);

            if (i < m_arrPkg.GetCount() - 1)
                summary += wxT("<br><hr width='90%' align='center'>");
        }

        summary +=  wxT("</body></html>");

        details = wxT("<html><body>")
                    wxT("<p>For details about a single package, select only that one.</p>")
                    wxT("</body></html>");
    }

    // update the summary HTML description
    m_pSummaryHtmlWin->SetPage(summary);

    // update the details HTML description
    m_pDetailsHtmlWin->SetPage(details);
}

void wxPackageViewerPanel::Reset()
{
    // default messages
    m_pSummaryHtmlWin->SetPage(m_strDefaultSummary);
    m_pDetailsHtmlWin->SetPage(m_strDefaultDetails);
}

bool wxPackageViewerPanel::Load(wxConfigBase *p, const wxString &path)
{
    m_arrDocs = wxString2Array(
    p->Read(path + wxT("/ViewerPanel/Files/ExtraHelpFiles"), wxT("pm.htb")));

    SetViewMode(p->Read(path + wxT("/ViewerPanel/ViewMode"), wxT("simple")));
    GetEmbeddedHelpController()->ReadCustomization(p, path + wxT("/EmbeddedHelp"));

    //m_embeddedHelpController->UseConfig(m_pCfg, m_strPath + wxT("/EmbeddedHelp"));
    return true;
}

void wxPackageViewerPanel::Save(wxConfigBase *p, const wxString &path) const
{
    p->Write(path + wxT("/ViewerPanel/Files/ExtraHelpFiles"), wxArray2String(m_arrDocs));
    p->Write(path + wxT("/ViewerPanel/ViewMode"), m_strViewModeName);

    GetEmbeddedHelpController()->WriteCustomization(p, path + wxT("/EmbeddedHelp"));
}


// ----------------------------------------------------------------------------
// wxPackageViewerPanel - event handlers
// ----------------------------------------------------------------------------

void wxPackageViewerPanel::OnLinkClicked(wxHtmlLinkEvent &ev)
{
    wxString href = ev.GetLinkInfo().GetHref();
    if (href == wxT("details"))
        SelectDetailsPage();
    else if (href == wxT("summary"))
        SelectSummaryPage();
    else if (href == wxT("docs"))
        SelectReferencePage();
    else
    {
#if wxPM_HAS_EMBEDDED_BROWSER
        SelectBrowserPage();
        GetBrowser()->LoadPage(href);
#else
        wxLaunchDefaultBrowser(href);
#endif
    }
}

void wxPackageViewerPanel::OnPageChanged(wxNotebookEvent &ev)
{
    static bool initialized = false;
    if (ev.GetSelection() == 2 && !initialized)
    {
        InitReference();
        initialized = true;
    }
}

