// WatkiRoboczeDlg.cpp : implementation file
//

#include "stdafx.h"
#include "WatkiRobocze.h"
#include "WatkiRoboczeDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CWatkiRoboczeDlg dialog




CWatkiRoboczeDlg::CWatkiRoboczeDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CWatkiRoboczeDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CWatkiRoboczeDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    DDX_Control(pDX, IDC_EDIT1, Edit1);
    DDX_Control(pDX, IDC_EDIT2, Edit2);
    DDX_Control(pDX, IDC_EDIT3, Edit3);
    DDX_Control(pDX, IDC_STATIC1, Label1);
    DDX_Control(pDX, IDC_COMBO1, ComboBox1);
    DDX_Control(pDX, IDC_COMBO2, ComboBox2);
}

BEGIN_MESSAGE_MAP(CWatkiRoboczeDlg, CDialog)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
    ON_BN_CLICKED(IDC_BUTTON1, &CWatkiRoboczeDlg::OnBnClickedButton1)
    ON_BN_CLICKED(IDC_BUTTON2, &CWatkiRoboczeDlg::OnBnClickedButton2)
    ON_BN_CLICKED(IDC_BUTTON3, &CWatkiRoboczeDlg::OnBnClickedButton3)
    ON_BN_CLICKED(IDC_BUTTON4, &CWatkiRoboczeDlg::OnBnClickedButton4)
    ON_BN_CLICKED(IDC_BUTTON5, &CWatkiRoboczeDlg::OnBnClickedButton5)
    ON_BN_CLICKED(IDC_BUTTON6, &CWatkiRoboczeDlg::OnBnClickedButton6)
    ON_BN_CLICKED(IDC_BUTTON7, &CWatkiRoboczeDlg::OnBnClickedButton7)
    ON_CBN_SELCHANGE(IDC_COMBO1, &CWatkiRoboczeDlg::OnCbnSelchangeCombo1)
    ON_BN_CLICKED(IDC_BUTTON8, &CWatkiRoboczeDlg::OnBnClickedButton8)
    ON_CBN_SELENDCANCEL(IDC_COMBO2, &CWatkiRoboczeDlg::OnCbnSelendcancelCombo2)
END_MESSAGE_MAP()


// CWatkiRoboczeDlg message handlers

BOOL CWatkiRoboczeDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here
    processPriority processPS[] = {
        {IDLE_PRIORITY_CLASS, L"IDLE_PRIORITY_CLASS"},
        {BELOW_NORMAL_PRIORITY_CLASS, L"BELOW_NORMAL_PRIORITY_CLASS"},
        {NORMAL_PRIORITY_CLASS, L"NORMAL_PRIORITY_CLASS"},
        {ABOVE_NORMAL_PRIORITY_CLASS, L"ABOVE_NORMAL_PRIORITY_CLASS"},
        {HIGH_PRIORITY_CLASS, L"HIGH_PRIORITY_CLASS"},
        {REALTIME_PRIORITY_CLASS, L"REALTIME_PRIORITY_CLASS"},
    };
	
    // Wypełnianie ComboBox1 i przedstawienie informacji 
    // o priorytecie aktualnego procesu
    int actualProcessClass = GetPriorityClass(GetCurrentProcess());
    
    for(int i = 0; i < sizeof(processPS)/sizeof(*processPS); i++)
    {
        ComboBox1.AddString(processPS[i].priorityName);
        ComboBox1.SetItemData(i, processPS[i].priority);
        if(processPS[i].priority == actualProcessClass)
            Label1.SetWindowTextW(processPS[i].priorityName);
    }

    threadPriority threadPS[] = {
        {THREAD_PRIORITY_ABOVE_NORMAL, L"THREAD_PRIORITY_ABOVE_NORMAL"},
        {THREAD_PRIORITY_BELOW_NORMAL, L"THREAD_PRIORITY_BELOW_NORMAL"},
        {THREAD_PRIORITY_HIGHEST, L"THREAD_PRIORITY_HIGHEST"},
        {THREAD_PRIORITY_IDLE, L"THREAD_PRIORITY_IDLE"},
        {THREAD_PRIORITY_LOWEST, L"THREAD_PRIORITY_LOWEST"},
        {THREAD_PRIORITY_NORMAL, L"THREAD_PRIORITY_NORMAL"},
        {THREAD_PRIORITY_TIME_CRITICAL, L"THREAD_PRIORITY_TIME_CRITICAL"},
    };
    
    // Wypełnianie ComboBox2 
    for(int i = 0; i < sizeof(threadPS)/sizeof(*threadPS); i++)
    {
        ComboBox2.AddString(threadPS[i].priorityName);
        ComboBox2.SetItemData(i, threadPS[i].priority);
    }

	return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CWatkiRoboczeDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CWatkiRoboczeDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

UINT FunkcjaPoczatkowa(LPVOID pParam)
{
    CWatkiRoboczeDlg::threadParams* params = (CWatkiRoboczeDlg::threadParams *) pParam;
    CString temp;
    HWND hWnd = FindWindowW(NULL, L"WatkiRobocze"); // Uchwyt do okna dialogowego
    LARGE_INTEGER startTime, endTime, freq;
    
    QueryPerformanceCounter(&startTime); // Czas początkowy
    QueryPerformanceFrequency(&freq); // Częstość
    
    if(params->its > 1)
    {
        for(int i = 1; i <= params->its; i++)
        {
            temp.Format(L"Indeks pętli = %d", i);
            SetDlgItemTextW(hWnd, IDC_EDIT1, temp);
            if(params->sleepTime != NULL)
                Sleep(params->sleepTime);
        }
    }           
    
    QueryPerformanceCounter(&endTime); // Czas końcowy
    
    __int64 totalTime = (endTime.QuadPart - startTime.QuadPart)*1000/freq.QuadPart; // Czas wykonania w ms
    
    temp.Format(L"Czas wykonywania wątku to: %d ms", totalTime);
    AfxMessageBox(temp);
    
    delete params;
    
    return 0; // Wywołanie funkcji wątku zakończyło się sukcesem
}

void CWatkiRoboczeDlg::OnBnClickedButton1()
{
    if(Edit2.GetWindowTextLengthW() > 0)
    {
        CString temp;
        int threadPriority = 0;
        threadParams *params = new threadParams;
        
        // Ilość iteracji
        Edit2.GetWindowTextW(temp);
        params->its = _wtoi(temp);
        params->sleepTime = NULL;
                
        // Czas uśpienia wątku
        if(Edit3.GetWindowTextLengthW() > 0)
        {
            int sleepTime;
            CString tempSleepTime;
            Edit3.GetWindowTextW(tempSleepTime); 
            sleepTime = _wtoi(tempSleepTime);
            if(sleepTime < 0) 
                AfxThrowUserException(); // Wyjątek można dopasować w zależności od potrzeb
            else
                params->sleepTime = sleepTime;
        }

        // Priorytet wątku
        CString tempThreadPriority;
        int index = ComboBox1.GetCurSel();
        if(index != CB_ERR)
            threadPriority = ComboBox1.GetItemData(index);

        // Uruchomienie wątku
        CWinThread *pThread = AfxBeginThread(FunkcjaPoczatkowa, params, threadPriority);
        uchwytWatku = pThread->m_hThread; // zachowujemy uchwyt wątku
    }
    else
        AfxMessageBox(L"Popraw ilość iteracji");
}

void CWatkiRoboczeDlg::OnBnClickedButton2()
{
    SuspendThread(uchwytWatku);
}

void CWatkiRoboczeDlg::OnBnClickedButton3()
{
    ResumeThread(uchwytWatku);
}

void CWatkiRoboczeDlg::OnBnClickedButton4()
{
    TerminateThread(uchwytWatku, -1);   
}

void CWatkiRoboczeDlg::OnBnClickedButton5()
{
    ExitThread(-1);
}

void CWatkiRoboczeDlg::OnBnClickedButton6()
{
    // Funkcja GetCurrentProcess() zwraca uchwyt do aktualnego procesu
    TerminateProcess(GetCurrentProcess(), -1);
}

void CWatkiRoboczeDlg::OnBnClickedButton7()
{
    ExitProcess(-1);
}

void CWatkiRoboczeDlg::OnCbnSelchangeCombo1()
{
    int index = ComboBox1.GetCurSel();
    
    if(!SetPriorityClass(GetCurrentProcess(), ComboBox1.GetItemData(index)))
    {
        HLOCAL hlocal = NULL;
        BOOL msg = FormatMessageW(
            FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | 
            FORMAT_MESSAGE_ALLOCATE_BUFFER,
            NULL, GetLastError(), MAKELANGID(LANG_POLISH, SUBLANG_POLISH_POLAND),
            (PTSTR)&hlocal, 0, NULL);
        
        if(msg && (hlocal != NULL))
            MessageBox((PCTSTR)LocalLock(hlocal));
        else
            MessageBox(L"Wystąpił nieznany błąd");
    }
    else
    {
        CString temp;
        ComboBox1.GetLBText(index, temp);
        Label1.SetWindowTextW(temp);
    }              
}

void CWatkiRoboczeDlg::OnBnClickedButton8()
{
    int threadPriority = GetThreadPriority(uchwytWatku);
    CString temp;
    
    for(int i = 0; i < ComboBox2.GetCount(); i++)
    {
        if(ComboBox2.GetItemData(i) == threadPriority)
            ComboBox2.GetLBText(i, temp);
    }
    AfxMessageBox(L"Priorytet aktualnie uruchomionego wątku to " + temp);
}

void CWatkiRoboczeDlg::OnCbnSelendcancelCombo2()
{
    DWORD exitCode;
    CString temp;
    GetExitCodeThread(uchwytWatku, &exitCode);
    
    if(exitCode == STILL_ACTIVE) // Czy wątek zakończył swoje działanie?
        if(!SetThreadPriority(uchwytWatku, ComboBox2.GetItemData(ComboBox2.GetCurSel())))
        {
            temp.Format(L"Próba zmiany priorytetu wątku nie powiodła się. Kod błędu: %d", GetLastError());
            AfxMessageBox(temp);
        }
        else ;
    else
        AfxMessageBox(L"Nie uruchomiono wątku roboczego");
}
