# -*- coding: utf-8 -*-
import Image
import os, sys
import math

# タイル画像を生成する
def create_tiles(basename, suffix, image, zoom):
    # グレーのベース画像を作っておく
    gray = Image.new("RGB", (256, 256), (231, 227, 222))

    try:
        os.mkdir("%s/%d" % (basename, zoom))
    except:
        pass

    (width, height) = image.size
    x_l = int(math.ceil(width/256.0))
    y_l = int(math.ceil(height/256.0))

    print "%d x %d tiles" % (x_l, y_l)

    for x in range(x_l):
        for y in range(y_l):
            tile = ""
            if (x == x_l-1 or y == y_l-1):
                # はじっこはサイズを 256x256 に整える
                tile = gray.copy()
                
                right = (x+1)*256
                low = (y+1)*256
                if right > width:
                    right = width
                if low > height:
                    low = height
                tile.paste(image.crop((x*256, y*256, right, low)), (0, 0))
            else:
                tile = image.crop((x*256, y*256, (x+1)*256, (y+1)*256))
            tile.save("%s/%d/%s_%s.%s" % (basename, zoom, x, y, suffix))

def create(basename, suffix, image):
    # タイル画像を保存するディレクトリを作成
    try:
        os.mkdir(basename)
    except:
        pass
    
    # 画像の pixel 数から zoom サイズを決める
    (width, height) = image.size
    length = float(height)
    if (width > height):
        length = float(width)
    length = length/256
    # log2(x)をもとめて zoom を決める
    zoom_size = int(math.ceil(math.log(length) / math.log(2)))

    (width, height) = image.size
    
    for count in range(zoom_size+1):
        zoom = zoom_size - count
        print "zoom", zoom

        map_image = ""
        if count != 0:
            # 1/2^n に縮小した画像を生成する
            map_image = image.resize((width/(2**count), height/(2**count)), Image.ANTIALIAS)
        else:
            map_image = image.copy()
        map_image.save("%s-%d.%s" % (basename, zoom, suffix))

        # 各 zoom 単位のタイル画像を生成する
        create_tiles(basename, suffix, map_image, zoom)

if __name__ == "__main__":
    try:
        # ファイル名を取得
        map_file = sys.argv[1]
        # ファイルの名前と拡張子に分離
        basename = os.path.basename(map_file)
        dot = basename.rfind(".")
        suffix = basename[dot+1:]
        basename = basename[:dot]

        # 画像を読み込む
        image = Image.open(map_file)
        # タイル画像を生成
        create(basename, suffix, image)
    except IndexError:
        print "Usage: create_tiles.py image_file"


