#!/usr/bin/env python
import gtk
import ggoggles
import sys

class SudokuGrid:
    # This callback quits the program
    def delete_event(self, widget, event, data=None):
        gtk.mainquit()
        return gtk.FALSE

    def __init__(self,original,solved):
        # Create a new window
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)

        # Set the window title
        self.window.set_title("Solved sudoku")

        # Set a handler for delete_event that immediately
        # exits GTK.
        self.window.connect("delete_event", self.delete_event)

        table = gtk.Table(9, 9, gtk.TRUE) 
        table.set_row_spacings(5)
        table.set_col_spacings(15)

        # Put the table in the main window
        self.window.add(table)
        solved_color = gtk.gdk.color_parse("red")


        for x in range(0,9):
            for y in range(0,9):

              cell = gtk.Label(solved[x+y*9])

              if original[x+y*9] == "0":
                 gtk.Widget.modify_fg (cell, gtk.STATE_NORMAL, solved_color);

              table.attach(cell, x, x+1, y, y+1)
              cell.show()


        table.show()
        self.window.show()

class ErrorWindow:
    def delete_event(self, widget, event, data=None):
        gtk.mainquit()
        return gtk.FALSE

    def __init__(self,message):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_title("Error")
        self.window.connect("delete_event", self.delete_event)

        self.label=gtk.Label(message)
        self.window.add(self.label)
        self.label.show()
        self.window.show()

def main():
    gtk.main()
    return 0       




if __name__ == "__main__":    
    if len(sys.argv) < 2:
        print "filename (jpeg) needed"
        sys.exit(1)
    filename = sys.argv[1]

    g = ggoggles.Goggles()
    res = g.process_image(filename)
    if res == None:
      #print "Error: process_image returns None, image might be too blur" 
      ErrorWindow("Error: process_image returns None, image might be too blur")
      main()
      sys.exit(1)

    print res  #debug
    
    #look at this string in result
    trigger = "http://www.google.com/goggles/a/sudoku?original="
    original = None

    for row in res.split("\n"):
        if trigger not in row:
            continue
        #print row
        i = row.index(trigger)
        i = i + len(trigger)
        #print i
        original = row[i:i+81]
        solved = row[i+81+8:i+81+8+81] #8 = len("&solved")

    if original == None:
       #print "Can't find sudoku in this photo"
       ErrorWindow("Can't find sudoku in this photo")
       main()
       sys.exit(1)

    SudokuGrid(original,solved)
    main()
