from PIL import Image
import glob, os

def filterThumbs(lStrings):
    return filter(lambda str: str.find('.thumbnail.jpg') < 0, lStrings)


def makeThumbPageTable(strPath, itemsPerRow=4, size=(160,120)):
    if(strPath[-1] != '/' and strPath[-1] != '\\'):
        strPath = strPath + '/'
    oFile = open(strPath+"index.html", "w")
    oFile.write('<html><head><title>Image listing</title></head>')
    oFile.write('<body text=\"#007fff\" vLink=\"#ff0000\" link=\"#ff0000\" bgColor=\"#000000\" hlink=\"#FF0000\">')
    oFile.write('<table>\n')
    nCnt = 0
    for infile in filterThumbs(glob.glob(strPath+"*.jpg")+glob.glob(strPath+"*.png")):
        if(nCnt == 0):
            oFile.write('\n<tr>')
        strFile, strExt = os.path.splitext(infile)
        im = Image.open(infile)
        im.thumbnail(size, Image.ANTIALIAS)
        im.save(strFile+".thumbnail.jpg","JPEG")
        strPrefix = strFile[len(strPath):]
        oFile.write('\n<td><a href=\"'+strPrefix+strExt+'\">')
        oFile.write('<img border=\"0\" src=\"'+strPrefix+'.thumbnail.jpg\"')
        oFile.write(' alt=\"'+strPrefix+'\">'+strPrefix+'</a></td>')
        if(nCnt == (itemsPerRow-1)):
            oFile.write('\n</tr>')
        nCnt = (nCnt+1) % itemsPerRow
    if(nCnt != 0):
        oFile.write('\n</tr>')
    oFile.write('\n</table>\n</body></html>\n')
    oFile.close()
    return

def makePhpInsert(strPath):
    size = (150,150)
    rowSize = 3
    if(strPath[-1] != '/' and strPath[-1] != '\\'):
        strPath = strPath + '/'
    strLastPart = strPath.split('/')[-2] + '/'
    oFile = open(strPath+"index.html", "w")
    oFile.write('<table>\n')
    nCnt = 0
    for infile in filterThumbs(glob.glob(strPath+"*.jpg")+glob.glob(strPath+"*.png")):
        if(nCnt == 0):
            oFile.write('\n<tr>')
        strFile, strExt = os.path.splitext(infile)
        im = Image.open(infile)
        im.thumbnail(size, Image.ANTIALIAS)
        im.save(strFile+".thumbnail.jpg","JPEG")
        strPrefix = strFile[len(strPath):]
        oFile.write('\n<td><a href=\"'+strLastPart+strPrefix+strExt+'\">')
        oFile.write('<img border=\"0\" src=\"'+strLastPart+strPrefix+'.thumbnail.jpg\"')
        oFile.write(' alt=\"'+strPrefix+'\">'+strPrefix+'</a></td>')
        if(nCnt == (rowSize-1)):
            oFile.write('\n</tr>')
        nCnt = (nCnt+1) % rowSize
    if(nCnt != 0):
        oFile.write('\n</tr>')
    oFile.write('\n</table>\n\n')
    oFile.close()
    return