#include <EDK.h>
#include "General.h"
#include "CC64.h"
#include <commdlg.h>
#include <dlgs.h>
#include <process.h>


extern CC64* gpC64;

static char acFileName[256];
static OPENFILENAME ofn;
static char acSelect[80];
static flag fOK;


UINT CALLBACK GetOpenFileNameHook(HWND hwnd, UINT uMsg, WPARAM /*wParam*/, LPARAM /*lParam*/) {
  if (uMsg == WM_INITDIALOG) {
    // select the current disk image in the listbox
    SendDlgItemMessage(hwnd, lst1, LB_SELECTSTRING, 0, (LPARAM)acSelect);
    // set the focus to the listbox
    PostMessage(hwnd, WM_NEXTDLGCTL, (WPARAM)GetDlgItem(hwnd, lst1), TRUE);
  }
  return FALSE;
}


void ChangeDisk3() {
  if (!fOK) {
    fOK = MessageBox(ghwnd, "Remove the disk from drive 8?", "Confirm", MB_ICONQUESTION | MB_OKCANCEL) != IDOK;
  }
  if (fOK) {
    SetDisk(&gpC64->IECMaster.apDevice[8], acFileName);
  }
  extern void ResumeFullscreen(HWND hwnd);
  ResumeFullscreen(ghwnd);
}


void __cdecl ChangeDisk2(void*) {
  fOK = GetOpenFileName(&ofn);
  PostMessage(ghwnd, WM_USER, 0, (LPARAM)ChangeDisk3);
  // in FrameWndProc:
  // case WM_USER:
  //   ((void (*)())lParam)();  <- I hate such typecasts!
  //   break;
}


void ChangeDisk() {

  extern void StopFullscreen(HWND hwnd);
  StopFullscreen(ghwnd);

  CIECDevice* pDevice = gpC64->IECMaster.apDevice[8];
  CString Dir;
  if (pDevice != NULL) {
    if (pDevice->GetType() != eVC1541) {
      return;
    }
    Dir = pDevice->GetDisk();
    pDevice->SetDisk("");
  }
  strncpy(acFileName, Dir, sizeof acFileName);

  char* pcSlash = strrchr(acFileName, '\\');
  if (pcSlash != NULL) {
    if (pcSlash[-1] == ':') {
      pcSlash++;
    }
    *pcSlash = 0;
    if (SetCurrentDirectory(acFileName)) {
      char ac[256];
      strcpy(ac, pcSlash + 1);
      strcpy(acFileName, ac);
    } else {
      *pcSlash = '\\';
    }
  }

  ofn.lStructSize = sizeof ofn;
  ofn.hwndOwner = ghwnd;
  ofn.hInstance = ghinst;
  ofn.lpstrFilter = "C64 Disk Images\0*.d64\0";
  ofn.lpstrCustomFilter = NULL;
  ofn.nMaxCustFilter = 0;
  ofn.nFilterIndex = 1;
  ofn.lpstrFile = acFileName;
  ofn.nMaxFile = sizeof acFileName;
  ofn.lpstrFileTitle = NULL;
  ofn.nMaxFileTitle = 0;
  ofn.lpstrInitialDir = NULL;
  ofn.lpstrTitle = "Change disk in drive 8";
  ofn.Flags = /*OFN_EXPLORER |*/ OFN_ENABLEHOOK;
  ofn.nFileOffset = 0;
  ofn.nFileExtension = 0;
  ofn.lpstrDefExt = "d64";
  ofn.lCustData = 0;
  ofn.lpfnHook = GetOpenFileNameHook;
  ofn.lpTemplateName = NULL;

  char* pc = strrchr(acFileName, '\\');
  if (pc != NULL) {
    pc++;
  } else {
    pc = acFileName;
  }
  strncpy(acSelect, pc, sizeof acSelect);

  DWORD dw = GetVersion();
  if ((dw & 0x80000000) && (BYTE)dw < 4) {
    ChangeDisk2(NULL);
  } else {
    _beginthread(ChangeDisk2, 0x4000, NULL);
  }
}
