/*
 * Copyright 2023 Google LLC
 *
 * 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.
 */

#include "risp4ml/common/utils.h"

// int GetBayerIndex(int x, int y) {
//   // The Bayer pattern code defines which color is top left in the quad:
//   // +---+---+
//   // | R | Gr|
//   // +---+---+
//   // | Gb| B |
//   // +---+---+
//   return ((x & 1) + 2 * (y & 1));
// }

BayerIndex GetBayerIndex(BayerPattern bayerType, uint16_t x, uint16_t y) {
  // The Bayer pattern code defines which color is top left in the quad:
  // 0: +---+---+ 1: +---+---+ 2: +---+---+ 3: +---+---+
  //    | R | Gr|    | Gr| R |    | Gb| B |    | B | Gb|
  //    +---+---+    +---+---+    +---+---+    +---+---+
  //    | Gb| B |    | B | Gb|    | R | Gr|    | Gr| R |
  //    +---+---+    +---+---+    +---+---+    +---+---+
  // pattern 0 is base pattern and other patterns are shifted versions of the
  // base

  // Patterns 1 and 3 shift in the x
  uint16_t x_shift = (uint16_t)(bayerType == kGrbg || bayerType == kBggr);
  // Patterns 2 and 3 shift in the y
  uint16_t y_shift = (uint16_t)(bayerType == kGbrg || bayerType == kBggr);
  return (BayerIndex)(((x + x_shift) & 1) + 2 * ((y + y_shift) & 1));
}

int BayerMirrorBoundary(int x, int size) {
  if (x < 0)
    return (-x + 2 * (-x & 0x1) - 2);
  else if (x < size)
    return x;
  else
    return 2 * size - x - 2 * ((x - size + 1) & 0x1);
}
