// grepWin - regex search and replace for Windows

// Copyright (C) 2012-2013, 2016-2017 - Stefan Kueng

// 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,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
#include "stdafx.h"
#include "resource.h"
#include "Settings.h"
#include <Commdlg.h>
#include "PathUtils.h"
#include "SearchDlg.h"	//+[JOJO] 58D8CCFF


CSettingsDlg::CSettingsDlg(HWND hParent)
    : m_hParent(hParent)
    , m_regEditorCmd(_T("Software\\grepWin\\editorcmd"))
{
}

CSettingsDlg::~CSettingsDlg(void)
{
}

LRESULT CSettingsDlg::DlgFunc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    UNREFERENCED_PARAMETER(lParam);
    switch (uMsg)
    {
    case WM_INITDIALOG:
        {
            InitDialog(hwndDlg, IDI_GREPWIN);
            CSearchDlg & searchDlg = *(CSearchDlg*) SendMessage(m_hParent, IDM_GETINSTANCE, 0, 0);	//+[JOJO] 58D8CCFF

            CLanguage::Instance().TranslateWindow(*this);

            SetDlgItemText(hwndDlg, IDC_EDITORCMD, bPortable ? g_iniFile.GetValue(L"global", L"editorcmd", L"") : std::wstring(m_regEditorCmd).c_str());

            std::wstring sPath;
            ////////////////////////////////////////////////////////////
            // [JOJO] modify
            std::wstring languagefile = searchDlg.languagefile;	//+[JOJO] 58DB84E9
            languagefile = CPathUtils::GetFileName(languagefile);	// without directory

            int index = 0;
            int langIndex = 0;
            m_langpaths.push_back(L"");
            SendDlgItemMessage(hwndDlg, IDC_LANGUAGE, CB_INSERTSTRING, (WPARAM)-1, (LPARAM)L"English (default)");
            WIN32_FIND_DATA findFileData;
            HANDLE hFindFile = FindFirstFile(CPathUtils::GetModulePath(L"*.lang").c_str(), &findFileData);
            if (hFindFile != INVALID_HANDLE_VALUE) {
                do {
                    if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY || findFileData.cFileName[0] == '.')
                        continue;
                    ++index;
                    m_langpaths.push_back(findFileData.cFileName);
                    SendDlgItemMessage(hwndDlg, IDC_LANGUAGE, CB_INSERTSTRING, (WPARAM)-1, (LPARAM)findFileData.cFileName);
                    if (StrCmpI(findFileData.cFileName, languagefile.c_str()) == 0)
                        langIndex = index;
                } while (FindNextFile(hFindFile, &findFileData));
                FindClose(hFindFile);
            }
            ////////////////////////////////////////////////////////////

            SendDlgItemMessage(hwndDlg, IDC_LANGUAGE, CB_SETCURSEL, langIndex, 0);
            SendDlgItemMessage(hwndDlg, IDC_ESCKEY, BM_SETCHECK, searchDlg.escclose ? BST_CHECKED : BST_UNCHECKED, 0);	//[JOJO] 58DDB703
            SendDlgItemMessage(hwndDlg, IDC_ENABLE_REPLACE, BM_SETCHECK, searchDlg.enableReplace ? BST_CHECKED : BST_UNCHECKED, 0);	//+[JOJO] 58D8CCFF
            SendDlgItemMessage(hwndDlg, IDC_BACKUPINFOLDER, BM_SETCHECK, bPortable ? !!_wtoi(g_iniFile.GetValue(L"settings", L"backupinfolder", L"0")) : DWORD(CRegStdDWORD(L"Software\\grepWin\\backupinfolder", FALSE)) ? BST_CHECKED : BST_UNCHECKED, 0);

            AddToolTip(IDC_BACKUPINFOLDER, TranslatedString(hResource, IDS_BACKUPINFOLDER_TT).c_str());


            m_resizer.Init(hwndDlg);
            m_resizer.AddControl(hwndDlg, IDC_EDITORGROUP, RESIZER_TOPLEFTRIGHT);
            m_resizer.AddControl(hwndDlg, IDC_EDITORCMD, RESIZER_TOPLEFTRIGHT);
            m_resizer.AddControl(hwndDlg, IDC_SEARCHPATHBROWSE, RESIZER_TOPRIGHT);	//+[JOJO] FIX
            m_resizer.AddControl(hwndDlg, IDC_STATIC1, RESIZER_TOPLEFTRIGHT);
            m_resizer.AddControl(hwndDlg, IDC_STATIC2, RESIZER_TOPLEFTRIGHT);
            m_resizer.AddControl(hwndDlg, IDC_STATIC3, RESIZER_TOPLEFT);
            m_resizer.AddControl(hwndDlg, IDC_STATIC4, RESIZER_TOPLEFT);
            m_resizer.AddControl(hwndDlg, IDC_LANGUAGE, RESIZER_TOPLEFT);
            m_resizer.AddControl(hwndDlg, IDC_ESCKEY, RESIZER_TOPLEFTRIGHT);
            m_resizer.AddControl(hwndDlg, IDC_BACKUPINFOLDER, RESIZER_TOPLEFTRIGHT);
            m_resizer.AddControl(hwndDlg, IDC_ENABLE_REPLACE, RESIZER_TOPLEFTRIGHT);	//+[JOJO] 58D8CCFF
            m_resizer.AddControl(hwndDlg, IDC_DWM, RESIZER_BOTTOMLEFT);
            m_resizer.AddControl(hwndDlg, IDOK, RESIZER_BOTTOMRIGHT);
            m_resizer.AddControl(hwndDlg, IDCANCEL, RESIZER_BOTTOMRIGHT);
            ExtendFrameIntoClientArea(0, 0, 0, IDC_DWM);
            m_aerocontrols.SubclassControl(GetDlgItem(*this, IDOK));
            m_aerocontrols.SubclassControl(GetDlgItem(*this, IDCANCEL));
            if (m_Dwm.IsDwmCompositionEnabled())
                m_resizer.ShowSizeGrip(false);
        }
        return TRUE;
    case WM_COMMAND:
        return DoCommand(LOWORD(wParam), HIWORD(wParam));
    case WM_SIZE:
        {
            m_resizer.DoResize(LOWORD(lParam), HIWORD(lParam));
        }
        break;
    case WM_GETMINMAXINFO:
        {
            MINMAXINFO * mmi = (MINMAXINFO*)lParam;
            mmi->ptMinTrackSize.x = m_resizer.GetDlgRectScreen()->right;
            mmi->ptMinTrackSize.y = m_resizer.GetDlgRectScreen()->bottom;
            return 0;
        }
        break;
    default:
        return FALSE;
    }
    return FALSE;
}

LRESULT CSettingsDlg::DoCommand(int id, int /*msg*/)
{
    switch (id)
    {
    case IDOK:
        {
            CSearchDlg & searchDlg = *(CSearchDlg*) SendMessage(m_hParent, IDM_GETINSTANCE, 0, 0);	//+[JOJO] 58D8CCFF
            auto buf = GetDlgItemText(IDC_EDITORCMD);
            if (bPortable)
                g_iniFile.SetValue(L"global", L"editorcmd", buf.get());
            else
                m_regEditorCmd = buf.get();
            int langIndex = (int)SendDlgItemMessage(*this, IDC_LANGUAGE, CB_GETCURSEL, 0, 0);
            std::wstring langpath = m_langpaths[langIndex];
            std::wstring languagefile = searchDlg.languagefile;	//+[JOJO] 58DB84E9
            searchDlg.languagefile = langpath;	//+[JOJO] 58DB84E9
            if (bPortable)
                g_iniFile.SetValue(L"global", L"languagefile", langpath.c_str());
            else
            {
                CRegStdString regLang(L"Software\\grepWin\\languagefile");
                if (langIndex==0)
                {
                    regLang.removeValue();
                }
                else
                {
                    regLang = langpath;
                }
            }
            ////////////////////////////////////////////////////////////
            // [JOJO]
            if (StrCmpI(CPathUtils::GetFileName(languagefile).c_str(), langpath.c_str()) != 0)	// without directory
            {
                CLanguage::Instance().LoadFile(CPathUtils::GetModulePath(langpath));
                if (languagefile.empty()) // from english to another language
                    CLanguage::Instance().TranslateWindow(m_hParent);
                else
                    bReload = TRUE;	// CSettingsDlg --> CSearchDlg --> WinMain
            }
            ////////////////////////////////////////////////////////////

            const bool escclose = IsDlgButtonChecked(*this, IDC_ESCKEY) == BST_CHECKED;
            searchDlg.escclose = escclose;	//[JOJO] 58DDB703

            const bool enableReplace = IsDlgButtonChecked(*this, IDC_ENABLE_REPLACE) == BST_CHECKED;
            searchDlg.enableReplace = enableReplace;	// [JOJO] 58D8CCFF
            searchDlg.CheckRegex();

            const bool backupinfolder = IsDlgButtonChecked(*this, IDC_BACKUPINFOLDER) == BST_CHECKED;

            if (bPortable)
            {
                g_iniFile.SetValue(L"global", L"escclose", escclose ? L"1" : L"0");
                g_iniFile.SetValue(L"global", L"enableReplace", enableReplace ? L"1" : L"0");
                g_iniFile.SetValue(L"settings", L"backupinfolder", backupinfolder ? L"1" : L"0");
            }
            else
            {
                CRegStdDWORD(L"Software\\grepWin\\escclose") = escclose;
                CRegStdDWORD(L"Software\\grepWin\\enableReplace") = enableReplace;
                CRegStdDWORD(L"Software\\grepWin\\backupinfolder") = backupinfolder;
            }

            ////////////////////////////////////////////////////////////
            // [JOJO]
            if (bReload)
                SendMessage(m_hParent, WM_CLOSE, 0, 0);
            ////////////////////////////////////////////////////////////
        }
        // fall through
    case IDCANCEL:
        EndDialog(*this, id);
        break;
    case IDC_SEARCHPATHBROWSE:
        {
            OPENFILENAME ofn = {0};     // common dialog box structure
            TCHAR szFile[MAX_PATH] = {0};  // buffer for file name
            // Initialize OPENFILENAME
            ofn.lStructSize = sizeof(OPENFILENAME);
            ofn.hwndOwner = *this;
            ofn.lpstrFile = szFile;
            ofn.nMaxFile = _countof(szFile);
            std::wstring sTitle = TranslatedString(hResource, IDS_SELECTEDITOR);
            ofn.lpstrTitle = sTitle.c_str();
            ofn.Flags = OFN_FILEMUSTEXIST|OFN_HIDEREADONLY|OFN_PATHMUSTEXIST|OFN_DONTADDTORECENT;
            auto sProgs = TranslatedString(hResource, IDS_PROGRAMS);
            auto sAllFiles = TranslatedString(hResource, IDS_ALLFILES);
            auto sFilter = sProgs;
            sFilter.append(L"\0*.exe;*.com\0", _countof(L"\0*.exe;*.com\0")-1);
            sFilter.append(sAllFiles);
            sFilter.append(L"\0*.*\0\0", _countof(L"\0*.*\0\0")-1);
            ofn.lpstrFilter = sFilter.c_str();
            ofn.nFilterIndex = 1;
            // Display the Open dialog box.
            if (GetOpenFileName(&ofn)==TRUE)
            {
                SetDlgItemText(*this, IDC_EDITORCMD, szFile);
            }
        }
        break;
    }
    return 1;
}

