#include "dialog/dlg_config.h"
#include "config.h" /* global config */
#include "plugin.h" /* update_rich_presence_details() */
#include "resource.h" /* TITLE_CHECK, ... */

#include <winuser.h>

#define conf_item_to_dlg(hwnd, cons, var) \
	do { \
		HWND checkboxHwnd = GetDlgItem(hwnd, cons); \
		SendMessage(checkboxHwnd, BM_SETCHECK, (var) ? BST_CHECKED : BST_UNCHECKED, 0); \
	} while (0);
#define dlg_item_to_conf(hwnd, cons, var) \
	do { \
		HWND checkboxHwnd = GetDlgItem(hwnd, cons); \
		(var) = (SendMessage(checkboxHwnd, BM_GETCHECK, 0, 0) == BST_CHECKED); \
	} while (0);
static void cfg_get_controls(HWND hWnd) {
	dlg_item_to_conf(hWnd, TITLE_CHECK,        config.display_title);
	dlg_item_to_conf(hWnd, ALBUM_ART_CHECK,    config.display_album_art);
	dlg_item_to_conf(hWnd, ALBUM_NAME_CHECK,   config.display_album_name);
	dlg_item_to_conf(hWnd, ARTIST_NAME_CHECK,  config.display_artist_name);
	dlg_item_to_conf(hWnd, SONG_INFO_CHECK,    config.display_song_info);
	dlg_item_to_conf(hWnd, ELAPSED_TIME_CHECK, config.show_elapsed_time);
}

static void cfg_set_controls(HWND hWnd) {
	conf_item_to_dlg(hWnd, TITLE_CHECK,        config.display_title);
	conf_item_to_dlg(hWnd, ALBUM_ART_CHECK,    config.display_album_art);
	conf_item_to_dlg(hWnd, ALBUM_NAME_CHECK,   config.display_album_name);
	conf_item_to_dlg(hWnd, ARTIST_NAME_CHECK,  config.display_artist_name);
	conf_item_to_dlg(hWnd, SONG_INFO_CHECK,    config.display_song_info);
	conf_item_to_dlg(hWnd, ELAPSED_TIME_CHECK, config.show_elapsed_time);
}
#undef conf_item_to_dlg
#undef dlg_item_to_conf

static void cfg_on_confirm_settings_dialog(HWND hWnd) {
	cfg_get_controls(hWnd);
	cfg_save(&config);
	update_rich_presence_details();
}

BOOL CALLBACK cfg_win_proc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
	switch (msg) {
		case WM_INITDIALOG:
			/* do nothing if this is a child window (tab page) callback, pass to the parent */
			if (GetWindowLong(hWnd, GWL_STYLE) & WS_CHILD)
				return FALSE;

			cfg_set_controls(hWnd);
			return TRUE;
		case WM_COMMAND:
			switch (LOWORD(wParam)) {
				case IDOK:
					cfg_on_confirm_settings_dialog(hWnd);
					EndDialog(hWnd, 0);
					return TRUE;
				case IDCANCEL:
					EndDialog(hWnd, 0);
					return TRUE;
			}
			break;
		default:
			break;
	}

	return FALSE;
}
