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

from __future__ import division

from django.conf import settings
from django.shortcuts import render

from account.models import UserInfo
from codes.models import CourseCodeInfo
from course.decorators import check_token
from courses.models import CourseInfo, CourseVideoInfo
from utils.error.errno_utils import CourseCodeStatusCode, CourseStatusCode, ProfileStatusCode
from utils.error.response_utils import response


@check_token
def course_info(request):
    user_id = request.GET.get('user_id', '')
    course_id = request.GET.get('course_id', '')

    try:
        user = UserInfo.objects.get(user_id=user_id, status=True)
    except UserInfo.DoesNotExist:
        return response(ProfileStatusCode.PROFILE_NOT_FOUND)

    try:
        course_code = CourseCodeInfo.objects.get(user_id=user.user_id, exchanged=True, status=True)
    except CourseCodeInfo.DoesNotExist:
        response(CourseCodeStatusCode.COURSE_CODE_NOT_FOUND)

    try:
        course = CourseInfo.objects.get(course_id=course_id)
    except CourseInfo.DoesNotExist:
        response(CourseStatusCode.COURSE_NOT_FOUND)

    videos = CourseVideoInfo.objects.filter(course=course, status=True).order_by('course_video_position')
    videos = [video.data for video in videos]

    video_count = len(videos)

    return render(request, 'page/course_info.html', {
        'domain': settings.DOMAIN,
        'video_default': videos[0] if video_count else '',
        'video_count': video_count,
        'videos': videos,
        'params': 'user_id={}&vtoken={}'.format(user_id, request.GET.get('vtoken', '')),
    })
