import os
import shutil
import xml.dom.minidom
import sys
sys.path.append(r'C:\Python27\lib\site-packages')
sys.path.append(r'C:\Python27\lib\site-packages\PIL')
from PIL import Image


def getOrigin(pixels, left, top, width, height):
    for x in xrange(left, left + width):
        for y in xrange(top, top + height):
            if pixels[x, y] == (255, 0, 255, 255):
                return (x - left, y - top)
    return (0, 0)


class Frame(object):
    def __init__(self, name, x, y, width, height, origin):
      self.name = os.path.splitext(name)[0]
      self.x = x
      self.y = y
      self.width = width
      self.height = height
      self.origin = origin

def main():
    if len(sys.argv) != 1:
        return
    #path = sys.argv[1]
    path = "goat"
    xmlPath = path + ".xml"
    imagePath = path + "_marked.png"
    image = Image.open(imagePath)
    pixels = image.load()
    if not os.path.exists(imagePath) or not os.path.exists(xmlPath):
        print "Provided path does not have a xml and png file."
        return
    sheetXml = xml.dom.minidom.parse(xmlPath)
    frames = []
    for node in sheetXml.childNodes:
        if not hasattr(node, "tagName") or node.tagName != "TextureAtlas":
            continue
        for sprite in node.childNodes:
            if not hasattr(sprite, "tagName") or sprite.tagName != "sprite":
                continue
            name = sprite.getAttribute('n')
            left = int(sprite.getAttribute('x'))
            top = int(sprite.getAttribute('y'))
            width = int(sprite.getAttribute('w'))
            height = int(sprite.getAttribute('h'))
            origin = getOrigin(pixels, left, top, width, height)
            frames.append(Frame(name, left, top, width, height, origin))
    for index, frame in enumerate(frames):
        if index % 5 == 0:
            end = min(index + 4, len(frames) - 1)
            print "#Frames {}-{}".format(index, end)
        print "render.data.frames.append(SpriteFrame({f.x}, {f.y}, {f.width}, {f.height}, Vector({f.origin[0]}, {f.origin[1]})))  # {f.name}".format(f=frame)

if __name__ == "__main__":
    main()
