import os
import shutil
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

TILE_SIZE = 16

def main():
    # if (len(sys.argv)) == 1 and not sys.argv[1].endswith('.png'):
    #     print "Need to provide the png file."
    #     return
    # path = sys.argv[1]
    # if not os.path.exists(path):
    #     print "Provided png file path does not exist."
    #     return
    path = "gold.png"
    variations = 3
    template = Image.open(path)
    width, height = template.size
    tileSize = height / variations
    assert (height % variations == 0)
    tileOffset = (tileSize - TILE_SIZE) / 2
    templatePixels = template.load()
    print tileOffset

    sideTileIndex = 0
    coreTileIndex = 1
    blendStartIndex = 2

    output = Image.new('RGBA', (tileSize * 20, tileSize * variations))
    outputPixels = output.load()

    coreTile = (tileOffset, tileOffset, TILE_SIZE, TILE_SIZE)
    top = (tileOffset, 0, TILE_SIZE, 2)
    right = (TILE_SIZE + tileOffset - 2, tileOffset, TILE_SIZE + tileOffset + 1, TILE_SIZE)
    bottom = (tileOffset, TILE_SIZE + tileOffset - 2, TILE_SIZE, TILE_SIZE + tileOffset + 1)
    left = (0, tileOffset, 2, TILE_SIZE)
    autotiles = [(top, right, bottom, left), (right, bottom, left), (top, bottom, left), (bottom, left), (top, right, left), \
                (right, left), (top, left), (left,), (top, right, bottom), (right, bottom), (top, bottom), (bottom,), (top, right), \
                (right,), (top,), ()]

    def copyContents(inputTile, variant, outputTile, area):
        inputX = inputTile * tileSize
        outputX = outputTile * tileSize
        startY = variant * tileSize
        for x in xrange(area[0], area[2]):
            for y in xrange(area[1], area[3]):
                print "Copying from input({}, {}) to output({}, {})".format(inputX + x, startY + y, outputX + x, startY + y)
                outputPixels[outputX + x, startY + y] = templatePixels[inputX + x, startY + y]

    for variant in xrange(variations):
        for index, autotile in enumerate(autotiles):
            #First copy over the base tile
            copyContents(coreTileIndex, variant, index, coreTile)
            for side in autotile:
                copyContents(sideTileIndex, variant, index, side)
        for x in xrange(4):
            copyContents(x + blendStartIndex, variant, 16 + x, coreTile)

    output.save("output.png")



if __name__ == "__main__":
    main()
