# -*- coding: utf-8 -*-

from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _

from pai2.basemodels import CreateUpdateMixin

import datetime
import os
import time


def upload_path(instance, old_filename):
    extension = os.path.splitext(old_filename)[1].lower()
    today = datetime.datetime.today()
    return 'file/{year}{month}/{timestamp}{extension}'.format(
        year=today.year,
        month=today.month,
        timestamp=time.time(),
        extension=extension
    )


class LatestAppInfo(CreateUpdateMixin):
    latest_version = models.CharField(_(u'latest_version'), max_length=255, help_text=u'最新版本')
    latest_app = models.FileField(_(u'latest_app'), upload_to=upload_path, blank=True, null=True, help_text=u'最新版 APP')
    latest_url = models.URLField(_(u'latest_url'), max_length=255, blank=True, null=True, help_text=u'最新版 APP 链接')

    class Meta:
        verbose_name = _('latestappinfo')
        verbose_name_plural = _('latestappinfo')

    def __unicode__(self):
        return u'{0.pk}'.format(self)

    @property
    def final_latest_url(self):
        return self.latest_url or u'{0}{1}'.format(settings.DOMAIN, self.latest_app and self.latest_app.url)

    def _data(self):
        return {
            'latest_version': self.latest_version,
            'latest_url': self.final_latest_url,
        }

    data = property(_data)


class SplashInfo(CreateUpdateMixin):
    splash_image = models.ImageField(_(u'splash_image'), upload_to=upload_path, blank=True, null=True, help_text=u'启动页面图片')
    spalash_image_airtime = models.DateTimeField(_(u'spalash_image_airtime'), blank=True, null=True, help_text=u'启动页面图片开始日期')
    spalash_image_deadline = models.DateTimeField(_(u'spalash_image_deadline'), blank=True, null=True, help_text=u'启动页面图片截止日期')

    class Meta:
        verbose_name = _('splashinfo')
        verbose_name_plural = _('splashinfo')

    def __unicode__(self):
        return u'{0.pk}'.format(self)

    @property
    def splash_image_url(self):
        return self.splash_image and (settings.DOMAIN + self.splash_image.url)

    def _data(self):
        return {
            'splash_image_url': self.splash_image_url,
            'spalash_image_airtime': self.spalash_image_airtime,
            'spalash_image_deadline': self.spalash_image_deadline,
        }

    data = property(_data)