# Copyright 2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.


from django.contrib.markup.templatetags.markup import textile
from django.db import models
from django import forms
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
from django.utils import simplejson

from feincms.admin.editor import ItemEditorForm
from feincms.module.page.models import Page
from feincms.module.medialibrary.models import MediaFile
from feincms.content.medialibrary.models import MediaFileWidget
from feincms.module.medialibrary.fields import MediaFileForeignKey


DEFAULT_JQ_TWITTER_URL = settings.MEDIA_URL + 'cloudcms/' + 'js/' + 'twitter/' + \
                        'jquery.twitter.js'
DEFAULT_LINKIFY_URL = settings.MEDIA_URL + 'cloudcms/' + 'js/' + 'twitter/' + \
                        'ba-linkify.js'
DEFAULT_JQ_TIMEAGO_URL = settings.MEDIA_URL + 'cloudcms/' + 'js/' + 'twitter/' + \
                        'jquery.timeago.js'
JQUERY_TWITTER_URL = getattr(settings, "JQUERY_TWITTER_URL",
        DEFAULT_JQ_TWITTER_URL)
LINKIFY_JS_URL = getattr(settings, "LINKIFY_JS_URL",
        DEFAULT_LINKIFY_URL)
JQUERY_TIMEAGO_URL = getattr(settings, "JQUERY_TIMEAGO_URL",
        DEFAULT_JQ_TIMEAGO_URL)

class VideoSection(models.Model):
    section_title = models.CharField(max_length=200, blank=True)
    video_title = models.CharField(max_length=200, blank=True)
    video_link = models.CharField(max_length=200, blank=True)
    video_width = models.PositiveIntegerField(default=700)
    video_height = models.PositiveIntegerField(default=550)
    image = MediaFileForeignKey(MediaFile, blank=True, null=True,
    related_name="as_image_for_video_section")
    image_hover = MediaFileForeignKey(MediaFile, blank=True, null=True,
            related_name="as_hover_for_video_section")
    alt_text = models.TextField(null=True, blank=True)
    extra_url_params = models.CharField(max_length=200, blank=True)

    class Meta:
        abstract = True
        verbose_name = _('video section')
        verbose_name_plural = _('video sections')

    def render(self, **kwargs):
        return render_to_string(['content/videosection.html'], {'content': self})


class TwitterFeed(models.Model):
    title = models.CharField(max_length=200, blank=True)
    account = models.CharField(max_length=200, blank=True)
    nots = models.CharField(max_length=200, help_text="Ugly words", blank=True)
    query = models.CharField(max_length=200, blank=True,
            help_text="Filter query")
    tag = models.CharField(max_length=200, blank=True, help_text="Hashtag")
    limit = models.PositiveIntegerField(default=10)
    replies = models.BooleanField(default=True)
    retweets = models.BooleanField(default=True)
    avatar = models.BooleanField(default=False)
    extra_params = models.TextField(blank=True,
            help_text="Json object to append to "
                      "JQuery-twitter-plugin settings. Change "
                      "this only if you know what you are doing.")

    class Meta:
        abstract = True
        verbose_name = _('twitter feed')
        verbose_name_plural = _('twitter feeds')

    @property
    def media(self):
        return forms.Media(js=(
                LINKIFY_JS_URL, JQUERY_TWITTER_URL, JQUERY_TIMEAGO_URL
            ))

    def js_conf(self):
        conf = {}
        if self.account:
            conf['from'] = self.account

        for f in ['nots', 'query', 'tag', 'limit', 'replies', 'retweets', 'avatar']:
            if type(getattr(self, f)) == bool:
                conf[f] = getattr(self, f)

            if getattr(self, f):
                conf[f] = getattr(self, f)

        xtraconf = {}
        try:
            xtraconf = simplejson.loads(self.extra_params)
        except:
            pass

        conf.update(xtraconf)
        return simplejson.dumps(conf)


    def render(self, **kwargs):
        return render_to_string(['content/twitter_feed.html'], {'content': self})


class AboutBlock(models.Model):

    title = models.CharField(max_length=200, blank=False)
    content = models.TextField(blank=False)
    image = MediaFileForeignKey(MediaFile, blank=True, null=True)
    image_position = models.CharField(max_length=200,
            choices=(('top', 'Top'), ('left', 'Left'), ('right', 'Right')))
    color = models.CharField(max_length=200, blank=False)
    offset_left = models.IntegerField(null=True, blank=True)
    offset_top = models.IntegerField(null=True, blank=True)

    class Meta:
        abstract = True
        verbose_name = _('about page block')
        verbose_name_plural = _('about page blocks')

    def render(self, **kwargs):
        return render_to_string(['content/about_block.html'], {'content': self})


class LoginForm(models.Model):
    """
    Login form
    """

    title = models.CharField(_('title'), max_length=200, blank=False)
    action_url = models.CharField(_('im url'), max_length=100, blank=False)
    display_forgot_password = models.BooleanField(default=False, null=False)
    next_url = models.CharField(max_length=255, null=True, blank=True)
    bottom_content = models.TextField(blank=True)
    logged_in_content = models.TextField(blank=True)

    class Meta:
        abstract = True
        verbose_name = _('login form')
        verbose_name_plural = _('login forms')

    def render(self, **kwargs):
        return render_to_string(['content/login_form.html'], {'content': self})


class IntroButton(models.Model):

    class Meta:
        abstract = True
        verbose_name = _('intro images')
        verbose_name_plural = _('intro images')

    image_1 = MediaFileForeignKey(MediaFile, blank=True, null=True,
            related_name="as_image1")
    image_2 = MediaFileForeignKey(MediaFile, blank=True, null=True,
            related_name="as_image2")
    image_3 = MediaFileForeignKey(MediaFile, blank=True, null=True,
            related_name="as_image3")
    link = models.CharField(max_length=255, blank=False, default="/welcome")
    link_title = models.CharField(max_length=255, blank=False, default="~okeanos")

    def render(self, **kwargs):
        return render_to_string(['content/intro_images.html'], {'content': self})


class TextileContent(models.Model):
    content = models.TextField()

    class Meta:
        abstract = True

    def render(self, **kwargs):
        return textile(self.content)
    
class IntroBlock(models.Model):
    title = models.CharField(_('title'), max_length=200, blank=False)
    content = models.TextField()
    class_name = models.CharField(_('class_name'), max_length=200, blank=True, null=True)
    image = MediaFileForeignKey(MediaFile, blank=True, null=True)

    class Meta:
        abstract = True

    def render(self, **kwargs):
        return render_to_string(['content/intro_block.html'], {'content': self})
    
