#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Inky-Calendar custom-functions for ease-of-use

Copyright by aceisace
"""
from PIL import Image, ImageDraw, ImageFont, ImageColor
from urllib.request import urlopen
import os
import time


##from glob import glob
##import importlib
##import subprocess as subp
##import numpy
##import arrow
##from pytz import timezone



##"""Set some display parameters"""
##driver = importlib.import_module('drivers.'+model)

# Get the path to the Inky-Calendar folder
top_level = os.path.dirname(
  os.path.abspath(os.path.dirname(__file__))).split('/inkycal')[0]

# Get path of 'fonts' and 'images' folders within Inky-Calendar folder
fonts_location = top_level + '/fonts/'
images = top_level + '/images/'

# Get available fonts within fonts folder
fonts = {}

for path,dirs,files in os.walk(fonts_location):
  for filename in files:
    if filename.endswith('.otf'):
      name = filename.split('.otf')[0]
      fonts[name] = os.path.join(path, filename)

    if filename.endswith('.ttf'):
      name = filename.split('.ttf')[0]
      fonts[name] = os.path.join(path, filename)

del name, filename, files

available_fonts = [key for key,values in fonts.items()]

def get_fonts():
  """Print all available fonts by name"""
  for fonts in available_fonts:
    print(fonts)

def write(image, xy, box_size, text, font=None, **kwargs):
  """Write text on specified image
  image = on which image should the text be added?
  xy = xy-coordinates as tuple -> (x,y)
  box_size = size of text-box -> (width,height)
  text = string (what to write)
  font = which font to use
  """

  allowed_kwargs = ['alignment', 'autofit', 'colour', 'rotation'
                    'fill_width', 'fill_height']
  alignment='center'
  autofit = False
  fill_width = 1.0
  fill_height = 0.8
  colour = 'black'
  rotation = None

  for key, value in kwargs.items():
    if key in allowed_kwargs:
      setattr(write, key, value)
    else:
      print('{0} does not exist'.format(key))
      pass

  x,y = xy
  box_width, box_height = box_size

  # Increase fontsize to fit specified height and width of text box
  if autofit == True or fill_width != 1.0 or fill_height != 0.8:
    size = 8
    font = ImageFont.truetype(font, size)
    text_width, text_height = font.getsize(text)[0], font.getsize('hg')[1]
    while (
      text_width < int(box_width * fill_width)
      ) and (
      text_height < int(box_height * fill_height)
      ):
        size += 1
        font = ImageFont.truetype(font, size)
        text_width, text_height = font.getsize(text)[0], font.getsize('hg')[1]

  text_width, text_height = font.getsize(text)[0], font.getsize('hg')[1]

  # Truncate text if text is too long so it can fit inside the box
  while (text_width, text_height) > (box_width, box_height):
    text=text[0:-1]
    text_width, text_height = font.getsize(text)[0], font.getsize('hg')[1]

  # Align text to desired position
  if alignment == "" or "center" or None:
    x = int((box_width / 2) - (text_width / 2))
  elif alignment == 'left':
    x = 0
  elif alignment == 'right':
    x = int(box_width - text_width)

  y = int((box_height / 2) - (text_height / 2))

  # Draw the text in the text-box
  draw  = ImageDraw.Draw(image)
  space = Image.new('RGBA', (box_width, box_height))
  ImageDraw.Draw(space).text((x, y), text, fill=colour, font=font)

  if rotation != None:
    space.rotate(rotation, expand = True)

  # Update only region with text (add text with transparent background)
  image.paste(space, xy, space)



def text_wrap(text, font=None, max_width = None):
  """Split long text (text-wrapping). Returns a list"""
  lines = []
  if font.getsize(text)[0] < max_width:
    lines.append(text)
  else:
    words = text.split(' ')
    i = 0
    while i < len(words):
      line = ''
      while i < len(words) and font.getsize(line + words[i])[0] <= max_width:
        line = line + words[i] + " "
        i += 1
      if not line:
        line = words[i]
        i += 1
      lines.append(line)
  return lines


def internet_available():
  """check if the internet is available"""
  try:
    urlopen('https://google.com',timeout=5)
    return True
  except URLError as err:
    return False


def get_system_tz():
  """Get the timezone set by the system"""
  try:
    local_tz = time.tzname[1]
  except:
    print('System timezone could not be parsed!')
    print('Please set timezone manually!. Setting timezone to None...')
    local_tz = None
  return local_tz