#include "bitmap_class.h"

bitmap_class::bitmap_class()
{
    vertex_buffer_ = 0;
    index_buffer_ = 0;
    texture_ = 0;
}


bitmap_class::bitmap_class(const bitmap_class& other)
{
}


bitmap_class::~bitmap_class()
{
}


bool bitmap_class::initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, int screenWidth, int screenHeight, char* textureFilename, int renderX, int renderY)
{
    LOG_INIT("Initializing bitmap class");

    bool result;

    // Store the screen size.
    screen_width_ = screenWidth;
    screen_height_ = screenHeight;

    // Store where the bitmap should be rendered to.
    render_x_ = renderX;
    render_y_ = renderY;

    // initialize the vertex and index buffer that hold the geometry for the bitmap quad.
    result = initialize_buffers(device);
    if (!result)
    {
        LOG_ERROR("Failed to initialize buffers");
        R_FALSE
    }

    // Load the texture for this bitmap.
    result = load_texture(device, deviceContext, textureFilename);
    if (!result)
    {
        LOG_ERROR("Failed to load texture");
        R_FALSE
    }

    LOG_INIT("Bitmap class initialized");

    R_TRUE
}

void bitmap_class::shutdown()
{
    // Release the bitmap texture.
    release_texture();

    // Release the vertex and index buffers.
    shutdown_buffers();

    return;
}

bool bitmap_class::render(ID3D11DeviceContext* deviceContext)
{
    bool result;

    // Update the buffers if the position of the bitmap has changed from its original position.
    result = update_buffers(deviceContext);
    if (!result)
    {
        LOG_ERROR("Failed to update buffers");
        R_FALSE
    }

    // Put the vertex and index buffers on the graphics pipeline to prepare them for drawing.
    render_buffers(deviceContext);

    R_TRUE
}

int bitmap_class::get_index_count()
{
    return index_count_;
}

ID3D11ShaderResourceView* bitmap_class::get_texture()
{
    return texture_->GetTexture();
}

bool bitmap_class::initialize_buffers(ID3D11Device* device)
{
    LOG_INIT("Initializing buffers");

    vertex_type* vertices;
    unsigned long* indices;
    D3D11_BUFFER_DESC vertexBufferDesc, indexBufferDesc;
    D3D11_SUBRESOURCE_DATA vertexData, indexData;
    HRESULT result;
    int i;

    // initialize the previous rendering position to negative one.
    prev_pos_x_ = -1;
    prev_pos_y_ = -1;

    // Set the number of vertices in the vertex array.
    vertex_count_ = 6;

    // Set the number of indices in the index array.
    index_count_ = vertex_count_;

    // Create the vertex array.
    vertices = new vertex_type[vertex_count_];

    // Create the index array.
    indices = new unsigned long[index_count_];

    // initialize vertex array to zeros at first.
    memset(vertices, 0, (sizeof(vertex_type) * vertex_count_));

    // Load the index array with data.
    for (i = 0; i < index_count_; i++)
    {
        indices[i] = i;
    }

    // Set up the description of the dynamic vertex buffer.
    vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    vertexBufferDesc.ByteWidth = sizeof(vertex_type) * vertex_count_;
    vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    vertexBufferDesc.MiscFlags = 0;
    vertexBufferDesc.StructureByteStride = 0;

    // Give the subresource structure a pointer to the vertex data.
    vertexData.pSysMem = vertices;
    vertexData.SysMemPitch = 0;
    vertexData.SysMemSlicePitch = 0;

    // Now finally create the vertex buffer.
    result = device->CreateBuffer(&vertexBufferDesc, &vertexData, &vertex_buffer_);
    if (FAILED(result))
    {
        LOG_ERROR("Failed to create vertex buffer");
        R_FALSE
    }

    // Set up the description of the index buffer.
    indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    indexBufferDesc.ByteWidth = sizeof(unsigned long) * index_count_;
    indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
    indexBufferDesc.CPUAccessFlags = 0;
    indexBufferDesc.MiscFlags = 0;
    indexBufferDesc.StructureByteStride = 0;

    // Give the subresource structure a pointer to the index data.
    indexData.pSysMem = indices;
    indexData.SysMemPitch = 0;
    indexData.SysMemSlicePitch = 0;

    // Create the index buffer.
    result = device->CreateBuffer(&indexBufferDesc, &indexData, &index_buffer_);
    if (FAILED(result))
    {
        LOG_ERROR("Failed to create index buffer");
        R_FALSE
    }

    // Release the arrays now that the vertex and index buffers have been created and loaded.
    delete[] vertices;
    vertices = 0;

    delete[] indices;
    indices = 0;

    LOG_INIT("Buffers initialized");

    R_TRUE
}

void bitmap_class::shutdown_buffers()
{
    LOG_SHUTDOWN("Shutting down buffers");

    // Release the index buffer.
    if (index_buffer_)
    {
        LOG_SHUTDOWN("Releasing index buffer");
        index_buffer_->Release();
        index_buffer_ = 0;
        LOG_SHUTDOWN("Index buffer released");
    }

    // Release the vertex buffer.
    if (vertex_buffer_)
    {
        LOG_SHUTDOWN("Releasing vertex buffer");
        vertex_buffer_->Release();
        vertex_buffer_ = 0;
        LOG_SHUTDOWN("Vertex buffer released");
    }

    LOG_SHUTDOWN("Buffers shut down");

    return;
}

bool bitmap_class::update_buffers(ID3D11DeviceContext* deviceContent)
{
    float left, right, top, bottom;
    vertex_type* vertices;
    D3D11_MAPPED_SUBRESOURCE mappedResource;
    vertex_type* dataPtr;
    HRESULT result;

    // If the position we are rendering this bitmap to hasn't changed then don't update the vertex buffer.
    if ((prev_pos_x_ == render_x_) && (prev_pos_y_ == render_y_))
    {
        R_TRUE
    }

    // If the rendering location has changed then store the new position and update the vertex buffer.
    prev_pos_x_ = render_x_;
    prev_pos_y_ = render_y_;

    // Create the vertex array.
    vertices = new vertex_type[vertex_count_];

    // Calculate the screen coordinates of the left side of the bitmap.
    left = (float)((screen_width_ / 2) * -1) + (float)render_x_;

    // Calculate the screen coordinates of the right side of the bitmap.
    right = left + (float)bitmap_width_;

    // Calculate the screen coordinates of the top of the bitmap.
    top = (float)(screen_height_ / 2) - (float)render_y_;

    // Calculate the screen coordinates of the bottom of the bitmap.
    bottom = top - (float)bitmap_height_;

    // Load the vertex array with data.
// First triangle.
    vertices[0].position = XMFLOAT3(left, top, 0.0f);  // Top left.
    vertices[0].texture = XMFLOAT2(0.0f, 0.0f);

    vertices[1].position = XMFLOAT3(right, bottom, 0.0f);  // Bottom right.
    vertices[1].texture = XMFLOAT2(1.0f, 1.0f);

    vertices[2].position = XMFLOAT3(left, bottom, 0.0f);  // Bottom left.
    vertices[2].texture = XMFLOAT2(0.0f, 1.0f);

    // Second triangle.
    vertices[3].position = XMFLOAT3(left, top, 0.0f);  // Top left.
    vertices[3].texture = XMFLOAT2(0.0f, 0.0f);

    vertices[4].position = XMFLOAT3(right, top, 0.0f);  // Top right.
    vertices[4].texture = XMFLOAT2(1.0f, 0.0f);

    vertices[5].position = XMFLOAT3(right, bottom, 0.0f);  // Bottom right.
    vertices[5].texture = XMFLOAT2(1.0f, 1.0f);

    // Lock the vertex buffer.
    result = deviceContent->Map(vertex_buffer_, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
    if (FAILED(result))
    {
        LOG_ERROR("Failed to map vertex buffer");
        R_FALSE
    }

    // Get a pointer to the data in the constant buffer.
    dataPtr = (vertex_type*)mappedResource.pData;

    // Copy the data into the vertex buffer.
    memcpy(dataPtr, (void*)vertices, (sizeof(vertex_type) * vertex_count_));

    // Unlock the vertex buffer.
    deviceContent->Unmap(vertex_buffer_, 0);

    // Release the pointer reference.
    dataPtr = 0;

    // Release the vertex array as it is no longer needed.
    delete[] vertices;
    vertices = 0;

    R_TRUE
}

void bitmap_class::render_buffers(ID3D11DeviceContext* deviceContext)
{
    unsigned int stride;
    unsigned int offset;


    // Set vertex buffer stride and offset.
    stride = sizeof(vertex_type);
    offset = 0;

    // Set the vertex buffer to active in the input assembler so it can be rendered.
    deviceContext->IASetVertexBuffers(0, 1, &vertex_buffer_, &stride, &offset);

    // Set the index buffer to active in the input assembler so it can be rendered.
    deviceContext->IASetIndexBuffer(index_buffer_, DXGI_FORMAT_R32_UINT, 0);

    // Set the type of primitive that should be rendered from this vertex buffer, in this case triangles.
    deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    return;
}

bool bitmap_class::load_texture(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* filename)
{
    bool result;


    // Create and initialize the texture object.
    texture_ = new texture_class;

    result = texture_->Initialize(device, deviceContext, filename);
    if (!result)
    {
        LOG_ERROR("Failed to initialize texture object");
        R_FALSE
    }

    // Store the size in pixels that this bitmap should be rendered at.
    bitmap_width_ = texture_->GetWidth();
    bitmap_height_ = texture_->GetHeight();

    R_TRUE
}

void bitmap_class::release_texture()
{
    LOG_SHUTDOWN("Releasing texture");
    // Release the texture object.
    if (texture_)
    {
        LOG_SHUTDOWN("Releasing texture object");
        texture_->Shutdown();
        delete texture_;
        texture_ = 0;
        LOG_SHUTDOWN("Texture object released");
    }

    LOG_SHUTDOWN("Texture released");

    return;
}

void bitmap_class::set_render_location(int x, int y)
{
    render_x_ = x;
    render_y_ = y;
    return;
}