#include <SFML/Copyright.hpp> // LICENSE AND COPYRIGHT (C) INFORMATION

////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "SFML/Window/Win32/CursorImpl.hpp"

#include "SFML/System/Err.hpp"
#include "SFML/System/Win32/WindowsHeader.hpp"

#include <cstring>


namespace sf::priv
{
////////////////////////////////////////////////////////////
CursorImpl::~CursorImpl()
{
    release();
}


////////////////////////////////////////////////////////////
CursorImpl::CursorImpl(CursorImpl&& rhs) noexcept : m_cursor(rhs.m_cursor), m_systemCursor(rhs.m_systemCursor)
{
    rhs.m_cursor       = nullptr;
    rhs.m_systemCursor = false;
}


////////////////////////////////////////////////////////////
CursorImpl& CursorImpl::operator=(CursorImpl&& rhs) noexcept
{
    if (&rhs != this)
    {
        m_cursor       = rhs.m_cursor;
        m_systemCursor = rhs.m_systemCursor;

        rhs.m_cursor       = nullptr;
        rhs.m_systemCursor = false;
    }

    return *this;
}


////////////////////////////////////////////////////////////
bool CursorImpl::loadFromPixels(const std::uint8_t* pixels, Vector2u size, Vector2u hotspot)
{
    release();

    // Create the bitmap that will hold our color data
    auto bitmapHeader           = BITMAPV5HEADER();
    bitmapHeader.bV5Size        = sizeof(BITMAPV5HEADER);
    bitmapHeader.bV5Width       = static_cast<LONG>(size.x);
    bitmapHeader.bV5Height      = -static_cast<LONG>(size.y); // Negative indicates origin is in upper-left corner
    bitmapHeader.bV5Planes      = 1;
    bitmapHeader.bV5BitCount    = 32;
    bitmapHeader.bV5Compression = BI_BITFIELDS;
    bitmapHeader.bV5RedMask     = 0x00ff0000;
    bitmapHeader.bV5GreenMask   = 0x0000ff00;
    bitmapHeader.bV5BlueMask    = 0x000000ff;
    bitmapHeader.bV5AlphaMask   = 0xff000000;

    std::uint32_t* bitmapData = nullptr;

    HDC     screenDC = GetDC(nullptr);
    HBITMAP color    = CreateDIBSection(screenDC,
                                     reinterpret_cast<const BITMAPINFO*>(&bitmapHeader),
                                     DIB_RGB_COLORS,
                                     reinterpret_cast<void**>(&bitmapData),
                                     nullptr,
                                     0);
    ReleaseDC(nullptr, screenDC);

    if (!color)
    {
        priv::err() << "Failed to create cursor color bitmap";
        return false;
    }

    // Fill our bitmap with the cursor color data
    // We'll have to swap the red and blue channels here
    std::uint32_t* bitmapOffset = bitmapData;
    for (std::size_t remaining = size.x * size.y; remaining > 0; --remaining, pixels += 4)
    {
        *bitmapOffset++ = static_cast<std::uint32_t>((pixels[3] << 24) | (pixels[0] << 16) | (pixels[1] << 8) | pixels[2]);
    }

    // Create a dummy mask bitmap (it won't be used)
    HBITMAP mask = CreateBitmap(static_cast<int>(size.x), static_cast<int>(size.y), 1, 1, nullptr);

    if (!mask)
    {
        DeleteObject(color);
        priv::err() << "Failed to create cursor mask bitmap";
        return false;
    }

    // Create the structure that describes our cursor
    auto cursorInfo     = ICONINFO();
    cursorInfo.fIcon    = FALSE; // This is a cursor and not an icon
    cursorInfo.xHotspot = hotspot.x;
    cursorInfo.yHotspot = hotspot.y;
    cursorInfo.hbmColor = color;
    cursorInfo.hbmMask  = mask;

    // Create the cursor
    m_cursor       = reinterpret_cast<HCURSOR>(CreateIconIndirect(&cursorInfo));
    m_systemCursor = false;

    // The data has been copied into the cursor, so get rid of these
    DeleteObject(color);
    DeleteObject(mask);

    if (m_cursor)
    {
        return true;
    }

    priv::err() << "Failed to create cursor from bitmaps";
    return false;
}


////////////////////////////////////////////////////////////
bool CursorImpl::loadFromSystem(Cursor::Type type)
{
    release();

    LPCTSTR shape = nullptr;

    // clang-format off
    switch (type)
    {
        case Cursor::Type::Arrow:                  shape = IDC_ARROW;       break;
        case Cursor::Type::ArrowWait:              shape = IDC_APPSTARTING; break;
        case Cursor::Type::Wait:                   shape = IDC_WAIT;        break;
        case Cursor::Type::Text:                   shape = IDC_IBEAM;       break;
        case Cursor::Type::Hand:                   shape = IDC_HAND;        break;
        case Cursor::Type::SizeHorizontal:         shape = IDC_SIZEWE;      break;
        case Cursor::Type::SizeVertical:           shape = IDC_SIZENS;      break;
        case Cursor::Type::SizeTopLeftBottomRight: shape = IDC_SIZENWSE;    break;
        case Cursor::Type::SizeBottomLeftTopRight: shape = IDC_SIZENESW;    break;
        case Cursor::Type::SizeLeft:               shape = IDC_SIZEWE;      break;
        case Cursor::Type::SizeRight:              shape = IDC_SIZEWE;      break;
        case Cursor::Type::SizeTop:                shape = IDC_SIZENS;      break;
        case Cursor::Type::SizeBottom:             shape = IDC_SIZENS;      break;
        case Cursor::Type::SizeTopLeft:            shape = IDC_SIZENWSE;    break;
        case Cursor::Type::SizeBottomRight:        shape = IDC_SIZENWSE;    break;
        case Cursor::Type::SizeBottomLeft:         shape = IDC_SIZENESW;    break;
        case Cursor::Type::SizeTopRight:           shape = IDC_SIZENESW;    break;
        case Cursor::Type::SizeAll:                shape = IDC_SIZEALL;     break;
        case Cursor::Type::Cross:                  shape = IDC_CROSS;       break;
        case Cursor::Type::Help:                   shape = IDC_HELP;        break;
        case Cursor::Type::NotAllowed:             shape = IDC_NO;          break;
    }
    // clang-format on

    // Get the shared system cursor and make sure not to destroy it
    m_cursor       = LoadCursor(nullptr, shape);
    m_systemCursor = true;

    if (m_cursor)
    {
        return true;
    }

    priv::err() << "Could not create copy of a system cursor";
    return false;
}


////////////////////////////////////////////////////////////
void CursorImpl::release()
{
    if (m_cursor && !m_systemCursor)
    {
        DestroyCursor(static_cast<HCURSOR>(m_cursor));
        m_cursor = nullptr;
    }
}

} // namespace sf::priv
