#include "displaywrapper.h"

DisplayWrapper DisplayWrapper::dwrapper;

#ifdef Q_OS_WIN32

DisplayWrapper::DisplayWrapper()
{
  base_height = base_width = 0;
  base_bpp = 0;

  DEVMODE devmode;
  int modenum = 0;
  WCHAR devname[1024];

  while (EnumDisplaySettings(devname, modenum, &devmode))
  {
    modeNames.append(QString::fromWCharArray(devname));
    modes.append(devmode);
    modenum++;
  }
}

DisplayWrapper::~DisplayWrapper()
{
}

bool DisplayWrapper::dw_switchMode(int w, int h, int bpp, bool fs)
{
  DEVMODE originalMode;
  originalMode.dmSize = sizeof(originalMode);

  EnumDisplaySettings(0,
            ENUM_CURRENT_SETTINGS,
            &originalMode);

  DEVMODE newMode = originalMode;

  // Changing the settings
  newMode.dmPelsWidth = (uint)w;
  newMode.dmPelsHeight = (uint)h;
  if (bpp > 0)
    newMode.dmBitsPerPel = (uint)bpp;

  DWORD flags = 0;
  if (fs) flags |= CDS_FULLSCREEN;
  long res = ChangeDisplaySettings(&newMode, flags);
  if (res == DISP_CHANGE_SUCCESSFUL) return true;

//  for (int i = 0; i < modes.size(); i++)
//  {
//    DEVMODE devmode = modes.at(i);
//    qDebug() << devmode.dmPelsWidth;
//    qDebug() << devmode.dmPelsHeight;
//    if (devmode.dmPelsWidth == w && devmode.dmPelsHeight == h)
//    {
//      if (bpp <= 0 || devmode.dmBitsPerPel == bpp)
//      {
//        devmode.dmFields = DM_DISPLAYFLAGS;
//        DWORD flags = 0;
//        if (fs) flags |= CDS_FULLSCREEN;
//        long res = ChangeDisplaySettings(&devmode, flags);
//        if (res == DISP_CHANGE_SUCCESSFUL) return true;
//        return false;
//      }
//    }
//  }
//

  return false;
}

void DisplayWrapper::dw_restoreMode()
{
  ChangeDisplaySettings(0,0);
}

#else

DisplayWrapper::DisplayWrapper()
{
  base_height = base_width = 0;
  base_bpp = 0;
}

DisplayWrapper::~DisplayWrapper()
{
}

bool DisplayWrapper::dw_switchMode(int w, int h, int bpp, bool fs)
{
  if (!base_height || !base_width)
  {
    XRRScreenConfiguration * info = XRRGetScreenInfo (QX11Info::display(), QX11Info::appRootWindow());
    if (!info)
      return false;

    int numSizes;
    XRRScreenSize * sizes = XRRConfigSizes(info, &numSizes);
    if (!numSizes)
      return false;

    base_width = sizes->width;
    base_height = sizes->height;

    XRRFreeScreenConfigInfo(info);
  }

//  int width_mm = (w / 96.0) * 25.4 + 0.5;
//  int height_mm = (h / 96.0) * 25.4 + 0.5;
//
//  XRRSetScreenSize(QX11Info::display(), QX11Info::appRootWindow(), w, h, width_mm, height_mm);

  QStringList args; args << "--size" << QString("%1x%2").arg(w).arg(h);
  QProcess::execute("xrandr", args);

  return true;
}

void DisplayWrapper::dw_restoreMode()
{
  if (base_height && base_width)
    dw_switchMode(base_width, base_height, base_bpp, true);
}

#endif
