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

#include "align.h"

void alignmentGetAxis(
  uint8_t align,
  float containerSize, float childSize, float childPos,
  float *outSize, float *outPos
) {
  if(align & ALIGN_SIZE_FILL) {
    *outSize = containerSize;
  } else if(align & ALIGN_SIZE_ORIGINAL) {
    *outSize = childSize;
  }

  if(align & ALIGN_POS_START) {
    *outPos = 0;
  } else if(align & ALIGN_POS_CENTER) {
    *outPos = (containerSize/2.0f) - ((*outSize) / 2.0f);
  } else if(align & ALIGN_POS_END) {
    *outPos = containerSize - (*outSize);
  }
}

align_t alignmentGet(
  uint8_t alignX, uint8_t alignY,
  float containerWidth, float containerHeight,
  float childWidth, float childHeight,
  float childX, float childY
) {
  align_t out = {
    .x = 0,
    .y = 0,
    .width = 0,
    .height = 0
  };

  if(alignX & ALIGN_SIZE_RATIO) {
    // Work out Y size and alignment first, then we base off that.
    alignmentGetAxis(
      alignY, containerHeight, childHeight, childY, &out.height, &out.y
    );

    // Now work out ratio
    out.width = out.height * (childWidth / childHeight);

    // Now do X
    alignmentGetAxis(
      alignX, containerWidth, childWidth, childX, &out.width, &out.x
    );
  } else {
    alignmentGetAxis(
      alignX, containerWidth, childWidth, childX, &out.width, &out.x
    );
  }
  
  // Same as above but inverted for Y axis.
  if(alignY & ALIGN_SIZE_RATIO) {
    alignmentGetAxis(
      alignX, containerWidth, childWidth, childX, &out.width, &out.x
    );
    out.height = out.width * (childHeight / childWidth);
    alignmentGetAxis(
      alignY, containerHeight, childHeight, childY, &out.height, &out.y
    );
  } else {
    alignmentGetAxis(
      alignY, containerHeight, childHeight, childY, &out.height, &out.y
    );
  }

  return out;
}