#include <iostream>
using namespace std;

#include "path.hpp"
#include "matrix.hpp"
//#include "list.hpp"


void buildRecursif(const matrix<char>& flood, matrix<char>& path, int start, int goal)
{
    if (start == goal)
        return;
        
    path.at(start) = '.';
    
    int cost = flood.at(start);
    
    if (top(start,14,10) && flood.at(up(start,14)) != 0 && flood.at(up(start,14)) < cost)
        buildRecursif(flood, path, up(start,14), goal);
    else if (bottom(start, 14, 10) && flood.at(down(start,14)) != 0 && flood.at(down(start,14)) < cost)
        buildRecursif(flood, path, down(start,14), goal);
    else if (borderL(start, 14, 10) && flood.at(left(start,14)) != 0 && flood.at(left(start,14)) < cost)
        buildRecursif(flood, path, left(start,14), goal);
    else if (borderR(start, 14, 10) && flood.at(right(start,14)) != 0 && flood.at(right(start,14)) < cost)
        buildRecursif(flood, path, right(start,14), goal);
}

bool recursifFlood(const matrix<char>& map, matrix<char>& path, int start, int goal, int cost)
{
    
    if (map.at(start) == '#')
        return false;
    if (path.at(start) != 0 && path.at(start) < cost)
        return false;
    path.at(start) = cost;
    if (start == goal)
        return true;

    
    if (top(start,14,10))
        recursifFlood(map, path, up(start,14), goal, cost+1);
    if (bottom(start, 14, 10))
        recursifFlood(map, path, down(start,14), goal, cost+1);
    if (borderL(start, 14, 10))
        recursifFlood(map, path, left(start,14), goal, cost+1);
    if (borderR(start, 14, 10))
        recursifFlood(map, path, right(start,14), goal, cost+1);
    
    return false;
}


int main()
{

    
/* MATRIX TEST */
    const char * sample = \
        "##############"\
        "#   #        #"\
        "#   # ####   #"\
        "#   #    #   #"\
        "#   ###      #"\
        "### #    #   #"\
        "#   # ####   #"\
        "#   #    #   #"\
        "#        #   #"\
        "##############";

    matrix<char>m(14,10);
    
    for (int i=0;i<140;i++)
        m.at(i) = *(sample+i);
    

    
    matrix<char>tmp(14,10);
    matrix<char>path(14,10);
    
    recursifFlood(m, tmp, index(2,2, 14), index(12,8, 14),'A');
    buildRecursif(tmp,path, index(12,8, 14),index(2,2, 14));

    for (int y=0;y<10;y++)
    {
        for (int x=0;x<14;x++)
            if (path.at(x,y) == '.')
                cout << path.at(x,y) << " ";
            else if (tmp.at(x,y) == 0)
                cout << m.at(x,y) << " ";
            else
                cout << "  ";//tmp.at(x,y) << " ";
        cout << endl;
    }

    return 0;
}
