/**
 * Copyright (c) 2021 Dominic Masters
 * 
 * This software is released under the MIT License.
 * https://opensource.org/licenses/MIT
 */

#include "frame.h"

void frameInit(frame_t *frame) {
  frame->x = 0;
  frame->y = 0;

  primitiveInit(
    &frame->primitive,
    QUAD_VERTICE_COUNT * FRAME_PRIMITIVE_COUNT,
    QUAD_INDICE_COUNT * FRAME_PRIMITIVE_COUNT
  );

  frameSetInnerSize(frame, FRAME_BORDER_SIZE*3, FRAME_BORDER_SIZE*3);
}

void frameSetSize(frame_t *frame, float width, float height) {
  frameSetInnerSize(frame,
    width - (FRAME_BORDER_SIZE * 2),
    height - (FRAME_BORDER_SIZE * 2)
  );
}

void frameSetInnerSize(frame_t *frame, float width, float height) {
  float rightStart = FRAME_BORDER_SIZE + width;
  float rightEnd = rightStart + FRAME_BORDER_SIZE;

  float bottomStart = FRAME_BORDER_SIZE + height;
  float bottomEnd = bottomStart + FRAME_BORDER_SIZE;

  float tw = 1.0f / 3.0f;
  float th = tw;

  // Buffer the top left edge
  quadBuffer(&frame->primitive, 0,
    0, 0, 0, 0,
    FRAME_BORDER_SIZE, FRAME_BORDER_SIZE, tw, th,
    0, 0
  );

  // Buffer the top edge.
  quadBuffer(&frame->primitive, 0,
    FRAME_BORDER_SIZE, 0, tw, 0,
    rightStart, FRAME_BORDER_SIZE, tw*2, th,
    QUAD_VERTICE_COUNT, QUAD_INDICE_COUNT
  );

  // Buffer the top right edge.
  quadBuffer(&frame->primitive, 0,
    rightStart, 0, tw*2, 0,
    rightEnd, FRAME_BORDER_SIZE, tw*3, th,
    QUAD_VERTICE_COUNT*2, QUAD_INDICE_COUNT*2
  );


  // Buffer the left edge
  quadBuffer(&frame->primitive, 0,
    0, FRAME_BORDER_SIZE, 0, th,
    FRAME_BORDER_SIZE, bottomStart, tw, th*2,
    QUAD_VERTICE_COUNT*3, QUAD_INDICE_COUNT*3
  );

  // Buffer the center
  quadBuffer(&frame->primitive, 0,
    FRAME_BORDER_SIZE, FRAME_BORDER_SIZE, tw, th,
    rightStart, bottomStart, tw*2, th*2,
    QUAD_VERTICE_COUNT*4, QUAD_INDICE_COUNT*4
  );

  // Buffer the right edge.
  quadBuffer(&frame->primitive, 0,
    rightStart, FRAME_BORDER_SIZE, tw*2, th,
    rightEnd, bottomStart, tw*3, th*2,
    QUAD_VERTICE_COUNT*5, QUAD_INDICE_COUNT*5
  );


  // Buffer the bottom left edge.
  quadBuffer(&frame->primitive, 0,
    0, bottomStart, 0, th*2,
    FRAME_BORDER_SIZE, bottomEnd, tw, th*3,
    QUAD_VERTICE_COUNT*6, QUAD_INDICE_COUNT*6
  );

  // Buffer the bottom edge.
  quadBuffer(&frame->primitive, 0,
    FRAME_BORDER_SIZE, bottomStart, tw, th*2,
    rightStart, bottomEnd, tw*2, th*3,
    QUAD_VERTICE_COUNT*7, QUAD_INDICE_COUNT*7
  );

  // Buffer the bottom right edge.
  quadBuffer(&frame->primitive, 0,
    rightStart, bottomStart, tw*2, th*2,
    rightEnd, bottomEnd, tw*3, th*3,
    QUAD_VERTICE_COUNT*8, QUAD_INDICE_COUNT*8
  );
}

void frameRender(frame_t *frame, shader_t *shader) {
  shaderUsePosition(shader, frame->x, frame->y, 0,  0, 0, 0);
  shaderUseTexture(shader, frame->texture);
  primitiveDraw(&frame->primitive, 0, -1);
}

void frameDispose(frame_t *frame) {
  primitiveDispose(&frame->primitive);
}