import matrix
import numpy as np
import shared
from pprint import pprint as pp
from queue import PriorityQueue
X = '.'

class Chiton:
    def __init__(self, name):
        self.load(name)
        self.y = 0
        self.x = 0
        self.values = []
        self.set_goal()

    def load(self, name):
        self.base = np.array(matrix.load_matrix_file(name))
        self.mx = self.base.copy()

    def walk(self):
        # Dijkstra from RedBlobGames
        start = (self.x,self.y)
        frontier = PriorityQueue()
        frontier.put(start, 0)
        came_from = dict()
        cost_so_far = dict()
        came_from[start] = None
        cost_so_far[start] = 0
        while not frontier.empty():
            current = frontier.get()
            if current == self.goal:
               break
            for _nxt in self.neighbors(current):
                nxt = (_nxt['x'],_nxt['y'])
                new_cost = cost_so_far[current] + _nxt['value']
                if nxt not in cost_so_far or new_cost < cost_so_far[nxt]:
                   cost_so_far[nxt] = new_cost
                   priority = new_cost
                   frontier.put(nxt, priority)
                   came_from[nxt] = current
        print(cost_so_far[self.goal])

    def neighbors(self, pos):
        return matrix.get_neighbors(self.mx, x=pos[0], y=pos[1], _dict=True)

    def pp(self):
        matrix.ppmx(self.mx,pad=False,space=False)
        print(self.x,self.y)

    def grow(self, size):
        ALL = [self.base.copy()]
        for x in range(25):
            n = ALL[-1].copy()
            n = self.increment(n)
            ALL.append(n)

        rows = []
        for x in range(5):
            rows.append(np.hstack(ALL[x:x+5]))

        grid = np.array(rows.pop(0))
        for row in rows:
            grid = np.vstack((grid,row))

        self.mx = grid
        self.set_goal()

    def set_goal(self):
        h,w = matrix.get_size(self.mx)
        self.goal = (h-1,w-1)

    def increment(self, row):
        row += 1
        row = np.where(row > 9, 1, row)
        return row



def main():
    c = Chiton(shared.get_fname(15))
    c.walk()
    c.grow(5)
    c.walk()


if __name__ == "__main__":
    main()
