/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: winguistage1.cpp,v 1.1.2.1 2004/07/09 02:03:06 hubbe Exp $
 * 
 * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved.
 * 
 * The contents of this file, and the files included with this file,
 * are subject to the current version of the RealNetworks Public
 * Source License (the "RPSL") available at
 * http://www.helixcommunity.org/content/rpsl unless you have licensed
 * the file under the current version of the RealNetworks Community
 * Source License (the "RCSL") available at
 * http://www.helixcommunity.org/content/rcsl, in which case the RCSL
 * will apply. You may also obtain the license terms directly from
 * RealNetworks.  You may not use this file except in compliance with
 * the RPSL or, if you have a valid RCSL with RealNetworks applicable
 * to this file, the RCSL.  Please see the applicable RPSL or RCSL for
 * the rights, obligations and limitations governing use of the
 * contents of the file.
 * 
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL") in which case the provisions of the GPL are applicable
 * instead of those above. If you wish to allow use of your version of
 * this file only under the terms of the GPL, and not to allow others
 * to use your version of this file under the terms of either the RPSL
 * or RCSL, indicate your decision by deleting the provisions above
 * and replace them with the notice and other provisions required by
 * the GPL. If you do not delete the provisions above, a recipient may
 * use your version of this file under the terms of any one of the
 * RPSL, the RCSL or the GPL.
 * 
 * This file is part of the Helix DNA Technology. RealNetworks is the
 * developer of the Original Code and owns the copyrights in the
 * portions it created.
 * 
 * This file, and the files included with this file, is distributed
 * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
 * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
 * ENJOYMENT OR NON-INFRINGEMENT.
 * 
 * Technology Compatibility Kit Test Suite(s) Location:
 *    http://www.helixcommunity.org/content/tck
 * 
 * Contributor(s):
 * 
 * ***** END LICENSE BLOCK ***** */

#include "hxtypes.h"

#if !(defined(_MSC_VER) && (_MSC_VER > 1100))
typedef int INT_PTR; // VC5 needs this, VC6 gets it from pnbastsd.h
#endif

#include <windows.h>
#include <commctrl.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <io.h>
#include <process.h>
#include <sys/stat.h>

#include "hxresult.h"

#include "wininstlib.h"
#include "package_info.h"

#include "resource.h"
#include "stage1.h"
#include "winstage1.h"
#include "winguistage1.h"

#define WM_HX_INSTALLPASS WM_USER


INT_PTR CALLBACK
ProgressDlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    if(!hwndDlg)
    {
        return FALSE;
    }

    switch(uMsg)
    {
        case WM_INITDIALOG:
        {
            return TRUE;
        }
        case WM_COMMAND:
        {
            switch(LOWORD(wParam))
            {
                case IDCANCEL:
                {
                    if(Stage1::g_pStage1)
                    {
                        //((WinGUIStage1*)(Stage1::g_pInstance))->OnCancel();
                        return TRUE;
                    }
                }                
            }
            break;
        }
        case WM_CLOSE:
        {
            if(Stage1::g_pStage1)
            {
                //Stage1::GetInstance()->OnCancel();
                return TRUE;
            }
        }        
    }

    return FALSE;
}

INT_PTR CALLBACK
PasswordDlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    if(!hwndDlg)
    {
        return FALSE;
    }

    switch(uMsg)
    {
        case WM_INITDIALOG:
        {
            return TRUE;
        }
        case WM_COMMAND:
        {
            switch(LOWORD(wParam))
            {
                case IDOK:
                {
                    if(Stage1::g_pStage1)
                    {
                        ((WinGUIStage1*)(Stage1::g_pStage1))->OnPassword();
                        return TRUE;
                    }
                }
                case IDCANCEL:
                {
                    DestroyWindow(hwndDlg);
                    PostQuitMessage(0);
                    return TRUE;
                }
            }
            break;
        }
        case WM_CLOSE:
        {
            DestroyWindow(hwndDlg);
            PostQuitMessage(0);
            return TRUE;
        }
    }

    return FALSE;
}

WinGUIStage1::WinGUIStage1() : WinStage1(),
    m_hInstance (NULL),
    m_hwndDlg(NULL),
    m_nPassAttempts(0),
    m_lpCmdLine(NULL),
    m_bCancelled(FALSE)
{
}

WinGUIStage1::~WinGUIStage1()
{
}

int
WinGUIStage1::Main(HINSTANCE hInstance, HINSTANCE hPrevInstance, 
                   LPSTR lpCmdLine, int nCmdShow, const char* szPass)
{
    int         argc;
    char**      argv;
    int i;

    m_lpCmdLine = lpCmdLine;

    // Convert from winmain style command line to argv
    ConvertCmdLine(lpCmdLine, argc, argv);    

    // Parse command line and return if necessary (-v or -h)
    if (ParseCmdLine(argc, argv))
    {
        return 0;
    }

    for(i = 1; i < argc; i++)
    {
        HX_VECTOR_DELETE(argv[i]);
    }
    HX_VECTOR_DELETE(argv);

    // Check the password if installer is password protected
    if(m_szPassword && strcmp(m_szUserPass, m_szPassword) != 0 &&
        ((m_ulInstFlags & INST_NON_INTERACTIVE) || !PasswordPrompt()))
    {
        return 0;
    }

    // Create the archive directory
    if(!MakeArchDir())
    {
        Cleanup();
        ReportError(ERR_TEMP_DIR);
        return -1;
    }

    // Get the archive
    BYTE* pArchive;
    m_ulArchiveSize = GetResource("ARCHIVE", pArchive);
    if(!m_ulArchiveSize || !pArchive)
    {
        Cleanup();
        ReportError(ERR_RES_LOAD);
        return -1;
    }

    // Display the Progress dialog
    if(!(m_ulInstFlags & INST_SILENT) && !ShowProgress())
    {
        Cleanup();
        ReportError(ERR_GENERAL);
        return -1;
    }

    HX_RESULT res = Dearchive(pArchive);
    
    if(FAILED(res))
    {
        Cleanup();
        ReportError(res == HXR_OUTOFMEMORY ? ERR_OUTOFMEMORY : ERR_DEARCH);
        return -1;
    }
    if (m_bCancelled)
    {
        Cleanup();
        return 0;
    }
    
    res = WinStage1::RunSecondStage();
    if(FAILED(res))
    {
        Cleanup();
        if(res == HXR_OUTOFMEMORY)
        {
            ReportError(ERR_OUTOFMEMORY);
        }
        else
        {
            ReportError(ERR_DEARCH);
        }
        return -1;
    }
    
    // Destroy the window
    if(m_hwndDlg)
    {
        DestroyWindow(m_hwndDlg);
        m_hwndDlg = NULL;
    }

    return 0;
}

void
WinGUIStage1::ReportError(const char* szError)
{
    // Message Box is owned by the main dialog (m_hwndDlg) if it exists.
    MessageBox(m_hwndDlg, szError, ERROR_TITLE, 
        MB_OK | MB_ICONWARNING | MB_APPLMODAL);
}

void
WinGUIStage1::PrintVersion(void)
{
    char szMsg[256];
    _snprintf(szMsg, 255, "%s Installer\n", PackageInfo::VersionString());
    szMsg[255] = '\0';

    MessageBox(NULL, szMsg, INFO_TITLE, MB_OK);
}

void
WinGUIStage1::PrintUsage(const char* szProg)
{
    char szMsg[4096];
    _snprintf(szMsg, 4095, 
        "%s Installer\n\nUsage: %s [options]\n\nWhere options are:\n%s\n",
        PackageInfo::VersionString(), szProg, 
        PackageInfo::CommandLineHelpString(m_szPassword ? TRUE : FALSE));
    szMsg[4095] = '\0';

    MessageBox(NULL, szMsg, INFO_TITLE, MB_OK);
}

BOOL
WinGUIStage1::ShowProgress(void)
{
    // Necessary for the progress bar
    InitCommonControls();

    m_hwndDlg = CreateDialog(m_hInstance, MAKEINTRESOURCE(IDD_PROGRESS), 0,
                                ProgressDlgProc);

    if(!m_hwndDlg)
    {
        return FALSE;
    }

    // Set the icon
    HICON hIcon = LoadIcon(m_hInstance, MAKEINTRESOURCE(IDI_SETUP));
    if(hIcon)
    {
        // Setting ICON_BIG actually sets both icons to the right one from 
        // this resource, whereas setting ICON_SMALL screws up the small one 
        SendMessage(m_hwndDlg, WM_SETICON,(WPARAM)(ICON_BIG),(LPARAM)hIcon);
    }

    // Set the window title
    SetWindowText(m_hwndDlg, PROGRESS_TITLE);

    return TRUE;
}

HX_RESULT
WinGUIStage1::UpdateProgress(UINT32 ulBytesDone)
{
    UINT16 nPercentDone = m_ulArchiveSize == 0 ? 0 :
        (UINT16)(((double)ulBytesDone / (double)m_ulArchiveSize + .5) * 100);

    // set the progress bar
    HWND hwndProgress = GetDlgItem(m_hwndDlg, IDC_PROGRESSBAR);
    if(hwndProgress)
    {
        PostMessage(hwndProgress, PBM_SETPOS, nPercentDone, 0);
    }    

    // Check if we're cancelled     
    CheckMessages();

    if(m_bCancelled)
    {
        return HXR_CANCELLED;
    }

    return HXR_OK;
}

void
WinGUIStage1::CheckMessages(void)
{
    MSG msg;
    while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
    {
	if(msg.message == WM_QUIT)
	{
	    m_bCancelled = TRUE;
	    break;
	}
	else if(!m_hwndDlg || !IsDialogMessage(m_hwndDlg, &msg))
	{
	    TranslateMessage(&msg);
	    DispatchMessage(&msg);
	}
    }
}

HX_RESULT
WinGUIStage1::RunSecondStageCmd(char* szCmd)
{
    //
    // check for install binary and run it.
    //

    HX_RESULT res = HXR_OK;
    struct stat info;
    STARTUPINFO startupInfo;
    PROCESS_INFORMATION procInfo;

    if(stat(szCmd, &info) != 0)
    {        
        return HXR_FAIL;
    }

    if(!m_lpCmdLine)
    {
        return HXR_FAIL;
    }

    // Add the stage2 exe path to the command line.
    char* szCmdLine = new char[strlen(szCmd) + strlen(m_lpCmdLine) + 4];
    if(!szCmdLine)
    {
        return HXR_OUTOFMEMORY;
    }
    sprintf(szCmdLine, "\"%s\" %s", szCmd, m_lpCmdLine);

    memset((void*)&startupInfo, 0, sizeof(STARTUPINFO));
    startupInfo.dwFlags = STARTF_USESHOWWINDOW;
    startupInfo.wShowWindow = SW_SHOW;

    if(!CreateProcess(NULL, szCmdLine, NULL, NULL, FALSE, 0, NULL, 
            NULL, &startupInfo, &procInfo))
    {
        if(GetLastError() == ERROR_NOT_ENOUGH_MEMORY)
        {
            res = HXR_OUTOFMEMORY;
        }
        else
        {
            res = HXR_FAIL;
        }
    }
    else
    {
        CloseHandle(procInfo.hProcess);
        CloseHandle(procInfo.hThread);
    }

    delete[] szCmdLine;
    return res;
}

BOOL
WinGUIStage1::PasswordPrompt()
{
    m_hwndDlg = CreateDialog(m_hInstance, MAKEINTRESOURCE(IDD_PASSWORD), 0,
                                PasswordDlgProc);

    if(!m_hwndDlg)
    {
        return FALSE;
    }

    // Set the icon
    HICON hIcon = LoadIcon(m_hInstance, MAKEINTRESOURCE(IDI_SETUP));
    if(hIcon)
    {
        // Setting ICON_BIG actually sets both icons to the right one from 
        // this resource, whereas setting ICON_SMALL screws up the small one 
        SendMessage(m_hwndDlg, WM_SETICON,(WPARAM)(ICON_BIG),(LPARAM)hIcon);
    }

    SetWindowText(m_hwndDlg, PASS_TITLE);

    //
    // Message Loop
    //
    MSG msg;
    BOOL bRet;
    while(bRet = GetMessage(&msg, NULL, 0, 0) != 0)
    {
        if(bRet == -1)
        {
            return FALSE;
        }
        else if(msg.message == WM_HX_INSTALLPASS)
        {
            return (BOOL)(msg.wParam);
        }
        else if(!IsDialogMessage(m_hwndDlg, &msg))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    return FALSE;
}

void
WinGUIStage1::OnPassword()
{
    GetDlgItemText(m_hwndDlg, IDC_PASSWORD, m_szUserPass, MAX_PASS);

    if(strcmp(m_szUserPass, m_szPassword) == 0)
    {
        // Close window and send password success (TRUE) message
        DestroyWindow(m_hwndDlg);
        PostMessage(NULL, WM_HX_INSTALLPASS, (WPARAM)TRUE, 0);
    }
    else
    {
        m_nPassAttempts++;

        if(m_nPassAttempts < MAX_PASS_ATTEMPTS)
        {
            // Display bad password error and clear input field
            MessageBox(m_hwndDlg, ERR_BAD_PASS, ERROR_TITLE, 
                MB_OK | MB_ICONWARNING);

            SetDlgItemText(m_hwndDlg, IDC_PASSWORD, "");
        }
        else
        {
            // Display max attempts error, close window, and send 
            // password failed (FALSE) message
            MessageBox(m_hwndDlg, ERR_MAX_PASS, ERROR_TITLE, 
                MB_OK | MB_ICONWARNING);

            DestroyWindow(m_hwndDlg);
            PostMessage(NULL, WM_HX_INSTALLPASS, (WPARAM)FALSE, 0);
        }
    }
}

