#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import unicode_literals, absolute_import, print_function

import time

from urlparse import urljoin

from django.db import models
from django.conf import settings
from django.utils import timezone

from gm_types.gaia import (
    VIDEO_CODE_STATUS,
    VIDEO_LIBRARY_VIDEO_TYPE,
)

from api.models.wordrel import WordRel


class VideoLibrary(models.Model):
    class Meta:
        verbose_name = u'视频库'
        db_table = 'api_video_library'

    source_id = models.IntegerField(verbose_name=u"关联id", db_index=True)
    raw_image_url = models.CharField(max_length=128, verbose_name=u"视频封面图地址")
    water_image_url = models.CharField(max_length=128, verbose_name=u"带图片水印的视频封面图地址", default='')
    raw_video_url = models.CharField(max_length=128, verbose_name=u"视频地址")
    water_video_url = models.CharField(max_length=128, verbose_name=u"带图片水印的视频地址", default="")
    persistent_id = models.CharField(max_length=128, verbose_name=u'七牛视频处理id', default="")
    persistent_status = models.IntegerField(verbose_name=u"七牛状态", choices=VIDEO_CODE_STATUS, default=VIDEO_CODE_STATUS.NOSTART)
    video_type = models.IntegerField(verbose_name=u"视频类型", choices=VIDEO_LIBRARY_VIDEO_TYPE)
    ordering = models.IntegerField(verbose_name=u"视频设置排序，越小越靠前", default=999)
    is_online = models.BooleanField(verbose_name=u"是否在线", default=True)
    # 视频截取转换 webp 格式
    persistent_clip_id = models.CharField(max_length=128, verbose_name=u'七牛视频截取处理id', default="")
    persistent_clip_status = models.IntegerField(default=VIDEO_CODE_STATUS.NOSTART, verbose_name=u"七牛截取状态")
    intercept_video_url = models.CharField(max_length=128, verbose_name=u"截取的视频地址", default="")
    webp_url = models.CharField(max_length=128, verbose_name=u'webp图片地址', default="")

    create_time = models.DateTimeField(verbose_name=u'创建时间', default=timezone.now)
    update_time = models.DateTimeField(verbose_name=u'更新时间', auto_now=True)

    def get_video_info(self):
        video_cover = self.water_image_url or self.raw_image_url
        video_url = self.water_video_url or self.raw_video_url

        if self.webp_url:
            short_video_url = self.webp_url
        else:
            short_video_url = ""

        return {
            "video_id": self.id,
            "video_cover": video_cover,
            "video_url": urljoin(settings.VIDEO_HOST, video_url),
            "short_video_url": short_video_url,
        }


class VideoRelationWord(models.Model):
    class Meta:
        verbose_name = u'视频库对应的新标签'
        db_table = 'api_video_relation_word'

    video = models.ForeignKey(VideoLibrary, verbose_name=u"视频")
    word = models.ForeignKey(WordRel, verbose_name=u"关键字")
