/*
 * This file is part of Afterwarp Framework (http://afterwarp.io).
 * Copyright (c) 2015 - 2023 Dr. Yuriy Kotsarenko. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 */

#ifdef _WIN32
  #include "resource.h"
  #include <SDKDDKVer.h>

  #define WIN32_LEAN_AND_MEAN
  #include <windows.h>
  // Remove conflicting Windows macros.
  #undef KEY_EXECUTE
#endif

#include <stdio.h>

#include "Afterwarp.h"
#include "Afterwarp.Vectors.h"

#define AFTERWARP_VECTORS_IMPLEMENTATION
#include "Afterwarp.Vectors.h"

// Global variables.

// Display characteristics.
static Point displaySize = {1280, 720};
static float displayScale = 1.0f;

// Base Afterwarp interfaces.
static Application* application = NULL;
static Device* device = NULL;
static SwapChain* swapChain = NULL;
static Canvas* canvas = NULL;
static TextRenderer* textRenderer = NULL;
static Timer* timer = NULL;

static Component* windowManager = NULL;

static ColorDithering* colorDithering = NULL;

// Forward declarations.

static void outputError(char const* message);

// Implementation.

LibraryBool applicationCreate(Application* application, void* user)
{
  device = DeviceCreate(application, DEVICE_TECHNOLOGY_UNKNOWN, 0);
  if (!device)
  {
    outputError("Could not create graphics device.");
    return false;
  }
  swapChain = SwapChainCreate(device, ApplicationGetWindowHandle(application), &displaySize,
    PIXEL_FORMAT_RGBA8, PIXEL_FORMAT_UNKNOWN, 0, false);
  if (!swapChain)
  {
    outputError("Could not create rendering swap-chain.");
    return false;
  }
  canvas = CanvasCreate(device);
  if (!canvas)
  {
    outputError("Could not create rendering canvas.");
    return false;
  }
  textRenderer = TextRendererCreate(canvas, &(Point){512, 512}, PIXEL_FORMAT_LA8, false);
  if (!textRenderer)
  {
    outputError("Could not create text rendering module.");
    return false;
  }
  colorDithering = ColorDitheringCreate(device);
  if (!colorDithering)
  {
    outputError("Could not create color dithering module.");
    return false;
  }
  timer = TimerCreate();
  if (!timer)
  {
    outputError("Could not create timer module.");
    return false;
  }
  windowManager = ComponentCreateWindowManager(application, canvas, textRenderer, "WindowManager", NULL,
    displayScale, PIXEL_FORMAT_UNKNOWN, 8, WINDOW_MANAGER_ATTRIBUTE_COMPOSITION);
  if (!windowManager)
  {
    outputError("Could not create window manager.");
    return false;
  }
  ComponentSetRect(windowManager, &(RectF){0.0f, 0.0f, displaySize.x, displaySize.y});

  Component* component = ComponentCreate(windowManager, "Panel", "MainPanel", NULL);
//  ComponentSetRect(component, &(RectF){0.0f, 0.0f, 256.0f, 256.0f});
  ComponentSetParent(component, windowManager);
  ComponentSetAlignment(component, COMPONENT_ALIGNMENT_CLIENT);

  component = ComponentCreate(windowManager, "Edit", "Edit1", NULL);
  ComponentSetRect(component, &(RectF){8.0f, 32.0f, 256.0f, 32.0f});
  ComponentSetParent(component, windowManager);

  component = ComponentCreate(windowManager, "Edit", "Edit2", NULL);
  ComponentSetRect(component, &(RectF){8.0f, 32.0f + 4.0f + 32.0f, 256.0f, 32.0f});
  ComponentSetParent(component, windowManager);

  return true;
}

void applicationDestroy(Application* application, void* user)
{
  ComponentDestroy(windowManager);
  TimerDestroy(timer);
  ColorDitheringDestroy(colorDithering);
  TextRendererDestroy(textRenderer);
  CanvasDestroy(canvas);
  SwapChainDestroy(swapChain);
  DeviceDestroy(device);
}

void applicationResize(Application* application, void* user)
{
  Rect clientRect = {0};
  ApplicationGetClientRect(application, &clientRect);

  displaySize = rectGetSize(clientRect);

  SwapChainResize(swapChain, &displaySize);
  ComponentSetRect(windowManager, &(RectF){0.0f, 0.0f, displaySize.x, displaySize.y});

//  ComponentUpdate(windowManager, 0.0f);
//  ApplicationInvalidate(application);
}

void applicationRender(Application* application, void* user)
{
  DeviceTechnology const technology = DeviceGetTechnology(device);

  bool const flipped = technology == DEVICE_TECHNOLOGY_OPENGL || technology == DEVICE_TECHNOLOGY_OPENGL_ES;
  Quad const texCoords = flipped ? quadFlip(quadUnity) : quadUnity;

  // Perform color dithering to eliminate color banding that results from conversion to 8-bit channels.
//  ColorDitheringSetFormat(colorDithering, COLOR_DITHERING_FORMAT_RGB8);
//  ColorDitheringExecuteTo(colorDithering, textureBlurredDithered, textureBlurred);
  if (ComponentUpdate(windowManager, TimerGetLatency(timer) / 1000000.0f))
    ApplicationInvalidate(application);

  ComponentPresent(windowManager);

  if (SwapChainBegin(swapChain))
  {
    FloatColor const clearColor = floatColor(0xFFE1E2E6u);
    DeviceClear(device, DEVICE_CLEAR_LAYER_COLOR, &clearColor, 1.0f, 0);

    if (CanvasBegin(canvas))
    {
      CanvasSetContextState(canvas, CANVAS_CONTEXT_STATE_FLAT_SCENE);

      // Draw final UI texture.
      Quad quad = makeQuad(0.0f, 0.0f, displaySize.x, displaySize.y);
      CanvasTexturedQuad(canvas, ComponentGetTexture(windowManager, WINDOW_MANAGER_TEXTURE_TYPE_SCREEN),
        &quad, &texCoords, &COLOR_RECT(0xFFFFFFFFu), BLENDING_EFFECT_COPY);

      // Prepare canvas for text output.
      CanvasSetContextState(canvas, CANVAS_CONTEXT_STATE_FLAT_TEXT);
      CanvasSetSamplerState(canvas, &(CanvasSamplerState){TEXTURE_FILTER_NEAREST, TEXTURE_FILTER_NEAREST});

      { // Draw technology string.
        FontParameters parameters = {
          .family = "Arial", .size = 16.0f * displayScale, .weight = FONT_WEIGHT_SEMI_BOLD,
          .stretch = FONT_STRETCH_NORMAL, .slant = FONT_SLANT_NONE, .effect = fontEffectDefault};
        parameters.effect.borderType = FONT_BORDER_SEMI_HEAVY;
        parameters.effect.borderBrightness = 1.0f;
        parameters.effect.fillBrightness = 0.0f;
        parameters.effect.shadowBrightness = 0.75f;
        parameters.effect.shadowOpacity = 1.0f;
        TextRendererSetFontParameters(textRenderer, &parameters);

        char const* const textDirect3D = "Direct3D (%d.%d+), features: %d.%d";
        char const* const textOpenGL = "OpenGL (%d.%d+), features: %d.%d";

        char const* const formatText = DeviceGetTechnology(device) == DEVICE_TECHNOLOGY_DIRECT3D ?
          textDirect3D : textOpenGL;

        char text[128];

        snprintf(text, sizeof(text), "Frame Rate: %1.0f", TimerGetFrameRate(timer));

        TextRendererDraw(textRenderer, &(PointF){12.0f * displayScale, 4.0f * displayScale}, text,
          &COLOR_PAIR(0xA0FFFFFFu), 1.0f, NULL);

        snprintf(text, sizeof(text), formatText,
          DeviceGetTechVersion(device) >> 8, (DeviceGetTechVersion(device) >> 4) & 0xF,
          DeviceGetTechFeatureVersion(device) >> 8, (DeviceGetTechFeatureVersion(device) >> 4) & 0xF);

        TextRendererDrawAligned(textRenderer, &(PointF){displaySize.x - 12.0f * displayScale,
          displaySize.y - 6.0f * displayScale}, text, &COLOR_PAIR(0xA0FFFFFFu), TEXT_ALIGNMENT_END,
          TEXT_ALIGNMENT_END, 1.0f, true, NULL);
      }
      CanvasEnd(canvas);
    }
    SwapChainEnd(swapChain);
  }
  TimerUpdate(timer);
}

void applicationMouse(Application* application, MouseEvent event, MouseButton button,
  Point const* position, void* user)
{
  ComponentAcceptMouse(windowManager, event, button,
    &(PointF){position->x / displayScale, position->y / displayScale});
}

void applicationKey(Application* application, KeyEvent event, int32_t virtualKey, uint16_t keyCode,
  void* user)
{
  if (event != KEY_EVENT_TYPING)
    ComponentAcceptKey(windowManager, event, ApplicationTranslateVirtualKey(application, virtualKey), 0);
  else
    ComponentAcceptKey(windowManager, event, 0, virtualKey);

  printf("Key.\n");
}

LibraryBool applicationIdle(Application* application, void* user)
{
  ApplicationInvalidate(application);
  return false;
}

void outputError(char const* message)
{
#ifdef _WIN32
  static char const* initErrorTitle = "Initialization Error";
  MessageBoxA(NULL, message, initErrorTitle, MB_ICONERROR | MB_OK | MB_DEFAULT_DESKTOP_ONLY);
#else
  printf("%s\n", message);
#endif
}

// Main application entry.

#ifdef _WIN32

int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prevInstance, _In_ LPWSTR cmdLine,
  _In_ int showCmd)
{
  UNREFERENCED_PARAMETER(prevInstance);
  UNREFERENCED_PARAMETER(cmdLine);
  UNREFERENCED_PARAMETER(showCmd);

  SetProcessDPIAware();

  char const* windowClassName = "AfterwarpDrawableTexturesDemo";

#else

int main(int argc, char **argv)
{

#endif

  ApplicationConfiguration configuration = {0};
  configuration.size = displaySize;
#ifdef _WIN32
  configuration.startup.win.handleInstance = instance;
  configuration.startup.win.handleIcon = LoadIcon(instance, MAKEINTRESOURCE(IDI_DRAWABLETEXTURES));

  strncpy(configuration.startup.win.windowClassName, windowClassName,
    sizeof(configuration.startup.win.windowClassName));
#else
  configuration.startup.nx.parameterCount = argc;
  configuration.startup.nx.parameterStrings = argv;
#endif

  application = ApplicationCreate(&configuration);
  if (!application)
  {
    outputError("Could not create Application object.");
    return -1;
  }

  ApplicationEvents events = {0};
  events.eventCreate = applicationCreate;
  events.eventDestroy = applicationDestroy;
  events.eventResize = applicationResize;
  events.eventRender = applicationRender;
  events.eventMouse = applicationMouse;
  events.eventKey = applicationKey;
  events.eventIdle = applicationIdle;

  ApplicationSetEvents(application, &events, NULL);

  displayScale = ApplicationGetWindowScale(application);

  if (displayScale > 1.0f + vectorEpsilon)
    ApplicationSetClientSize(application,
      &(Point){(int32_t)(displaySize.x * displayScale), (int32_t)(displaySize.y * displayScale)});

  ApplicationSetTitle(application, "Afterwarp: GUI test application");

  { // Retrieve client size back in case it has changed since startup.
    Rect clientRect = {0};
    ApplicationGetClientRect(application, &clientRect);

    displaySize = rectGetSize(clientRect);
  }

  bool const executed = ApplicationExecute(application);
  ApplicationDestroy(application);

  return executed ? 0 : -1;
}