# -*- Mode: Python; -*-
# -*- coding: utf-8 -*-
# vi:si:et:sw=2:sts=2:ts=2

import os
from os.path import abspath, exists, join, dirname
import Image

from scrapeit.utils import read_url

cache_root = join(dirname(abspath(__file__)), 'cache')
img_extension = "png"

def loadFile(f_name):
  f = open(f_name)
  data = f.read()
  f.close()
  return data

def saveFile(f_name, data):
  f = open(f_name, 'w')
  f.write(data)
  f.close()

'''
  returns name including a possible directory level for a given hash
'''
def imgName(hashId):
  return "%s/%s.%s" % (hashId[:16], hashId, img_extension)

'''
  returns path to an icon from iconType for given icon in the cache
'''
def iconPath(iconType, item):
  icon_root = join(cache_root, iconType)
  icon = join(icon_root, imgName(item.hashId))
  if not exists(dirname(icon)):
    os.makedirs(dirname(icon))
  return icon

'''
  render reflection of sourceFile on targetFile, 
  uses alpha, target files needs to support RGBA, i.e. png
'''
def _writeReflection(sourceFile, targetFile, height = 0.5, opacity = 0.25):
  sourceImage = Image.open(sourceFile).convert('RGB')
  sourceSource = sourceImage.size[0]
  sourceHeight = sourceImage.size[1]

  targetWidth = sourceImage.size[0]
  targetHeight = int(round(sourceHeight * height))
  targetImage = Image.new('RGBA', (targetWidth, targetHeight))

  for y in range(0, targetHeight):
    brightness = int(255 * (targetHeight - y) * opacity / targetHeight)
    for x in range(0, targetWidth):
      targetColor = sourceImage.getpixel((x, sourceHeight - 1 - y)) 
      targetColor += (brightness, )
      targetImage.putpixel((x, y), targetColor)
  targetImage.save(targetFile, optimized = True)

'''
  return icon data, reads from remote url if not cached
'''
def loadIcon(item):
  icon = iconPath('icon', item)
  if exists(icon):
    data = loadFile(icon)
  else:
    data = read_url(item.icon)
    saveFile(icon, data)
  return data

'''
  return icon reflection data, renders reflection if it does not exists
'''
def loadIconReflection(item):
  icon = iconPath('icon', item)
  iconReflection = iconPath('iconReflection', item)
  if not exists(iconReflection):
    if not exists(icon):
      icon(item)
    if exists(icon):
      _writeReflection(icon, iconReflection)
    else:
      return ''
  return loadFile(iconReflection)

'''
  return icon data, reads from remote url if not cached
'''
def loadArchiveIcon(archive):
  icon = iconPath('archiveIcon', archive)
  if exists(icon):
    data = loadFile(icon)
  else:
    data = read_url(archive.icon)
    saveFile(icon, data)
  return data

