# simulation.py
# 15110
# This program is provided as a partial implementation of PA10
#
# fire_wall_n() is NOT IMPLEMENTED and should be added to this
#   file to complete part 3 of PA10

import tkinter
from tkinter import Canvas      # get graphics functions
from random import *            # get seed() and randrange()
from time import *              # get sleep()
from display import display     # get display command
from update import update       # get update command

def random_forest(sideLength):
    # initialize a forest matrix randomly
    forest = []
    # construct n rows and append each row to forest
    for i in range(sideLength):
        row = []
        for j in range(sideLength):
            row.append(randrange(5))
        forest.append(row)
    return forest

                       
def fire_wall_forest(sideLength):
    # initialize forest with a wall of fire in row 0
    forest = []
    # construct n rows and append each row to forest
    for i in range(sideLength):
        row = []
        for j in range(sideLength):
            # nothing here is initialized to zero (on fire)
            row.append(randrange(1, 5))
        forest.append(row)
    # replace the first row with all zeros (on fire)
    forest[0] = [0] * sideLength
    return forest
    


def run_simulation(step = False, init = 'random'):
    # run a forest fire simulation, 
    #    step is True to prompt for "Enter" key before
    #         running each simulation step
    #   init can be 'wall' to initialize the top row to FIRE or
    #         'n' to initialize first n cells to FIRE, where n
    #         is read in from the console. Default is 'random'
    #         which means all cells are randomly initialized.
    #       
    # first, seed the random number generator
    seed(15110)
    
    # set the number of rows (=cols of the matrix
    sideLength = 17
    
    window = tkinter.Tk()   
    # create a canvas (of size 340 X 340 for 17x17 matrix)
    c = Canvas(window, width=sideLength*20, height=sideLength*20)
    c.pack() 
    
    if init == 'wall':
        forest = fire_wall_forest(sideLength)
    elif init == 'n': # this option is not implemented yet
        forest = fire_wall_n()
    else:
        forest = random_forest(sideLength)
    
    display(forest, c)
    for i in range(100):
        if step:
            answer = input("Press Enter to continue (q/Q to Quit): ")
            if answer == 'q' or answer == 'Q':
                return None   #Exit from the function
        else:
            sleep(0.1)
        forest = update(forest)
        display(forest, c)


