#!/usr/bin/python

#    Kye - classic puzzle game
#    Copyright (C) 2005, 2006 Colin Phipps <cph@moria.org.uk>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

from kye.editframe import KEditFrame
from kye.leveledit import KLevelEdit
from kye.common import kyepaths, tryopen
from string import upper
from os import unlink, fdopen
from tempfile import mkstemp
import sys

def openfile(fname, template = 0):
    global gamestate,g,tfname,tf,newlevel
    playfile = fname
    try:
        gamefile = tryopen(fname, kyepaths)
        g = KLevelEdit(gamefile, disp = f.canvas, newleveltemplate=newlevel, setlevellist = f.setlevels, hintmenuitems = f.hintmenuitems)
        f.palette.set_target(g)
        if template == 0: f.setfname(fname)
    except IOError, e:
        f.error_message(message="Failed to read "+fname)
    try:
        tf.seek(0)
        tf.truncate()
        g.saveto(tf)
    except IOError, e:
        f.error_message(message="Failed to write backup copy %s" % tf.name)        
    return True

def savefile(fname):
    f = open(fname, 'wb')
    g.saveto(f)
    f.close()
    g.saved()

def doonlevel(f,**h):
    if g != None:
        return getattr(g,f)(**h)
    else:
	return None

f = KEditFrame(opencall = openfile, savecall = savefile, palsource = KLevelEdit.cell_lookup, levelcall = doonlevel)

def get_template_board():
    fname="template.kye"
    try:
        gamefile = tryopen(fname, kyepaths)
        g = KLevelEdit(gamefile, disp = f.canvas, newleveltemplate = None)
    except IOError, e:
        f.error_message(message="Failed to read "+fname)
	raise
    return g.levels[0]

newlevel = get_template_board()
if len(sys.argv)>1:
    playfile = sys.argv[1]
    template = 0
else:
    playfile = "template.kye"
    template = 1

g = None
(tf,tfname) = mkstemp(suffix='.kye')
tf = fdopen(tf, 'w')
openfile(playfile, template=template)

g.saveto(tf)
f.main()

# If out without errors, remove the backup copy
tf.close()
unlink(tfname)
