#!/usr/bin/env python3
#******************************************************************************
# Copyright (C) 2018 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
# This file is part of the textoutpc project, which is MIT-licensed.
#******************************************************************************

from ..tags import TextoutBlockTag as _TextoutBlockTag
from html import escape as _htmlescape

__all__ = ["TextoutImageTag", "TextoutAdminImageTag"]

class TextoutImageTag(_TextoutBlockTag):
	""" The main tag for displaying an image.
		Example uses:
	
		[img]picture_url[/img]
		[img=center]picture_url[/img]
		[img=12x24]picture_url[/img]
		[img=center|12x24]picture_url[/img]
		[img=x24|right]picture_url[/img]
	"""

	aliases = ('[img]',)
	raw = True

	def prepare(self, name, value):
		self._width = None
		self._height = None
		self._align = None
		self._float = False

		for arg in ("", value)[value != None].split('|'):
			if   not arg:
				pass
			elif arg[0] in '0123456789x':
				self._width = None
				self._height = None

				dim = arg.split('x')
				try:    self._width = int(dim[0])
				except: pass
				try:    self._height = int(dim[1])
				except: pass
			elif arg in ('center', 'left', 'right'):
				self._align = arg
			elif arg in ('float-left', 'float-right'):
				self._align = arg[6:]
				self._float = True
			elif arg in ('float', 'floating'):
				self._float = True

	def preprocess(self, content):
		for prefix in ('http://', 'https://', 'ftp://', '/'):
			if content.startswith(prefix):
				break
		else:
			raise Exception("No allowed prefix!")

		self._url = content

	def content_html(self):
		style = []
		cls = []
		if   self._width:
			style.append('width: {}px'.format(self._width))
		elif self._height:
			style.append('width: auto')
		if   self._height:
			style.append('height: {}px'.format(self._height))
		elif self._width:
			style.append('height: auto')
		if   self._float:
			cls.append('img-float')
		if   self._align:
			cls.append('img-{}'.format(self._align))

		return '<img src="{}"{}{} />'.format(\
			_htmlescape(self._url),
			' class="{}"'.format(' '.join(cls)) if cls else '',
			' style="{}"'.format('; '.join(style)) if style else '')

	def content_lightscript(self):
		url = self._url.replace('[', '%5B').replace(']', '%5D')
		return '[[image:{}]]'.format(url)

class TextoutAdminImageTag(TextoutImageTag):
	""" This tag is special for Planète Casio, as it takes images from
		the `ad`ministration's image folder.
		It just adds this folder's prefix.
		Example uses:
		
		[adimg]some_picture.png[/img]
		[adimg=center]some_picture.png[/img]
		[adimg=12x24]some_picture.png[/img]
		[adimg=center|12x24]some_picture.png[/img]
		[adimg=x24|right]some_picture.png[/img]
	"""

	aliases = ('[adimg]',)

	def preprocess(self, content):
		path = content
		# FIXME: check image URL!
		self._url = 'https://www.planet-casio.com/images/ad/' + path

# End of file.
