/***************************************************************************
 *   Copyright (C) 2005 by Thierry CHARLES   *
 *   thierry@les-charles.net   *
 *                                                                         *
 *   This program 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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program 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 this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "tools_panelelt.h"

#include <wx/filefn.h>
#include <wx/colordlg.h>
#include <wx/regex.h>
#include <wx/intl.h>

#include "components/codeeditor/tcodeeditor.h"
#include "components/framework/tapplicationpanel.h"
#include "components/framework/tapplication.h"
#include "components/framework/tmainwindow.h"
#include "components/stdgui/tpanel.h"
#include "components/stdgui/tbitmap.h"
#include "components/stdgui/tgenbutton.h"
#include "xpe_components/mainwindow.h"
#include "xpe_components/editor/editor_panelelement.h"

#include "xpe_components/dlg/color_dlg.h"

#include "lib/tcolor.h"
#include "lib/lib_string.h"
#include "lib/lib_logging.h"

#include "bmp_id.h"

ToolsPanelElement::ToolsPanelElement(TApplicationPanel * _owner, int iID)
    : ToolbarPanelElement(_owner, iID)
{
    this->addButton( 1, GET_BMP(BMP_FILE_OPEN_22_ID), wxT(""), wxTr("retrive filename"), false);
    this->addButton( 2, GET_BMP(BMP_COLORCHOOSER_22_ID), wxT(""), wxTr("get color"), false);
}

ToolsPanelElement::~ToolsPanelElement()
{
}

// void ToolsPanelElement::buttonActivated(TGenButton * btn)
void ToolsPanelElement::buttonClicked(int iButtonID, bool bStateDown)
{
    if(!getMainWindowCenterPanel())
        return;

    EditorPanelElement * editor = dynamic_cast<EditorPanelElement *>( getMainWindowCenterPanel()->getFirstVisibleElement());
    if(!editor)
        return;

    wxString sSelection = editor->getEditor()->getSelectedText();

    if(iButtonID == 1)
    {
        static wxString sLastDir;
        static wxString sFilters = wxSTr("Povray scripts") + wxT(" (*.pov)|*.pov|")
                + wxSTr("Povray includes") + wxT(" (*.inc)|*.inc|")
                + wxSTr("Povray ini") + wxT(" (*.ini)|*.ini|")
                + wxSTr("Fonts") + wxT(" (*.ttf)|*.ttf|")
                + wxSTr("Images") + wxT(" (*.png;*.jpg;*.jpeg;*.tif;*.tiff;*.gif;*.ppm;*.tga;*.pgm)|*.png;*.jpg;*.jpeg;*.tif;*.tiff;*.gif;*.ppm;*.tga;*.pgm;*.PNG;*.JPG;*.JPEG;*.TIF;*.TIFF;*.GIF;*.PPM;*.TGA;*.PGM|")
                + wxSTr("All files") + wxT(" (*;*.*)|*;*.*");

        wxString sDir = wxPathOnly(sSelection);
        if(!sDir.length())
            sDir = sLastDir;
        wxFileDialog * dlg = new wxFileDialog(dynamic_cast<wxWindow *>(this->getOwner()->getOwner()), wxTr("Choose a file"), sDir, sSelection, sFilters,wxOPEN|wxFILE_MUST_EXIST);
        int iRes = dlg->ShowModal();
        if(iRes == wxID_OK)
        {
            sLastDir = wxPathOnly(dlg->GetPath());

            // rechercher le fichier dans la liste des paths
/*            QString path = filename.left(filename.findRev('/') + 1);
            if (pathsList.find(TPathListItem(true,path)) != pathsList.end())
                activeTabTextEditor->insert(filename.mid(filename.findRev(QDir::separator()) + 1));*/
            // obtenir un nom de fichier relatif au fichier en cours d'édition
/*            else if (useRelativePaths)
                activeTabTextEditor->insert(
                        getRelativePath(
                        activeFileName.left(activeFileName.findRev(QDir::separator())),
            filename));*/
//             else
            editor->getEditor()->eraseSelection();
            editor->getEditor()->insert(dlg->GetPath());
        }
        delete dlg;
    }
    else if(iButtonID == 2)
    {
        static const wxString sDECIMAL_POINT = wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT,wxLOCALE_CAT_NUMBER);
        static const wxRegEx color_expr(wxT("((rgb[[:blank:]]+)?<[[:blank:]]*[0-9]+\\.?[0-9]*[[:blank:]]*,[[:blank:]]*[0-9]+\\.?[0-9]*[[:blank:]]*,[[:blank:]]*[0-9]+\\.?[0-9]*[[:blank:]]*>)"));

        TColor col(128,128,128);
        if(color_expr.Matches(sSelection))
        {
            double fRed = 0.0, fGreen=0.0, fBlue=0.0, fMax=1.0;
            sSelection = color_expr.GetMatch(sSelection);

            sSelection = sSelection.AfterFirst('<');
            wxString s = sSelection.BeforeFirst(',');
            s.Trim(true).Trim(false);
#ifndef __WXMSW__
            s.Replace(wxT("."),sDECIMAL_POINT);
#endif
            s.ToDouble(&fRed);
            if (fMax < fRed)
                fMax = fRed;
            sSelection = sSelection.AfterFirst(',');
            s = sSelection.BeforeFirst(',');
            s.Trim(true).Trim(false);
#ifndef __WXMSW__
            s.Replace(wxT("."),sDECIMAL_POINT);
#endif
            s.ToDouble(&fGreen);
            if (fMax < fGreen)
                fMax = fGreen;
            sSelection = sSelection.AfterFirst(',');
            s = sSelection.BeforeFirst('>');
            s.Trim(true).Trim(false);
#ifndef __WXMSW__
            s.Replace(wxT("."),sDECIMAL_POINT);
#endif
            s.ToDouble(&fBlue);
            if (fMax < fBlue)
                fMax = fBlue;

            fMax = 1.0;
            col = TColor(uint(fRed*255.0/fMax),uint(fGreen*255.0/fMax),uint(fBlue*255.0/fMax));
        }

        ColorDlg * dlg = new ColorDlg(dynamic_cast<wxWindow *>(this->getOwner()->getOwner()));
        if(dlg->show(col))
        {
            col = dlg->getColor();

            wxString s;
            wxString sCol = wxString(wxT("rgb < "));
            s = wxString::Format(wxT("%.3f"),col.getDecimalRed());
            s.Replace(sDECIMAL_POINT,wxT("."));
            sCol += s + wxT(" , ");
            s = wxString::Format(wxT("%.3f"),col.getDecimalGreen());
            s.Replace(sDECIMAL_POINT,wxT("."));
            sCol += s + wxT(" , ");
            s = wxString::Format(wxT("%.3f"),col.getDecimalBlue());
            s.Replace(sDECIMAL_POINT,wxT("."));
            sCol += s + wxT(" >");

            editor->getEditor()->eraseSelection();
            editor->getEditor()->insert(sCol);
        }
        delete dlg;
    }
    editor->getEditor()->SetFocus();
}

