#include "vision.h"
using namespace std;

std::vector<int> getVisionPattern1d()
{
    return {1, 2, 3};
}

//extern void myAssert(bool cond, const char* msg);

int getMove1d(std::vector<int> v)
{
    int center = v[v.size()/2];
    if(center == 1) {
        if(v[0] == 3) return 2;
        return 0;
    }
    if(center == 2) {
        if(v[0] == 3) return 4;
        return 0;
    }
    if(v[4] == 1) return 6;
    return 0;
}

std::vector<std::vector<int>> getVisionPattern2d()
{
    return {{2, 1, 2},
            {1, 1, 1},
            {2, 1, 1}};
}

std::pair<int, int> getMove2d(std::vector<std::vector<int>> v)
{
    int center = v.size()/2;
    pair<int, int> normal = {center+1, center+1};
    pair<int, int> xflip = {center-1, center+1};
    pair<int, int> yflip = {center+1, center-1};
    pair<int, int> xyflip = {center-1, center-1};
    bool flipped_x = false;
    bool flipped_y = false;

    if(center == 1) {
        pair<int, int> twos[3];

        int curtwo = 0;
        for(int x = 0; x < v.size(); x++) {
            for(int y = 0; y < v.size(); y++) {
                if(v[x][y] == 2) {
                    twos[curtwo++] = {x, y};
                }
            }
        }
        //myAssert(curtwo == 3, "failed");
        int pivot = 2; //center of the right angle formed by the 3 twos
        if((twos[0].first == twos[1].first && twos[0].second == twos[2].second) || (twos[0].first == twos[2].first && twos[0].second == twos[1].second)) {
            pivot = 0;
        } else if ((twos[1].first == twos[2].first && twos[1].second == twos[0].second) || (twos[1].first == twos[0].first && twos[1].second == twos[2].second)) {
            pivot = 1;
        }

        for(int i = 0; i < 3; i++) {
            if(i == pivot) continue;
            if(twos[i].first - twos[pivot].first == -2 || twos[i].first - twos[pivot].first == 1) flipped_x = true;
            if(twos[i].second - twos[pivot].second == -2 || twos[i].second - twos[pivot].second == 1) flipped_y = true;
        }
        if(flipped_x && flipped_y) {
            return xyflip;
        } else if(flipped_x) {
            return xflip;
        } else if(flipped_y) {
            return yflip;
        }
        return normal;
    }

    vector<vector<int>> squished;
    for(int i = 1; i < 4; i++) {
        vector<int> row;
        for(int j = 1; j < 4; j++) {
            row.push_back(v[i][j]);
        }
        squished.push_back(row);
    }
    pair<int, int> res = getMove2d(squished);
    res.first++;
    res.second++;
    return res;
}
