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

from django.conf import settings
from django.shortcuts import redirect
from logit import logit

from account.models import UserInfo
from operation.models import FeedbackInfo, SplashInfo
from utils.error.errno_utils import UserStatusCode
from utils.error.response_utils import response
from utils.redis.rapp import get_latest_app
from utils.redis.rsettings import get_app_settings_info


@logit
def upgrade_api(request):
    """ APP 升级 """
    src = int(request.POST.get('src', 0))

    latest_app = get_latest_app(src)

    if request.iOS:
        appinfo = {
            'latest_version_code': latest_app.get('latest_ios_version_code', ''),
            'latest_version_name': latest_app.get('latest_ios_version_name', ''),
            'latest_url': latest_app.get('latest_ios_url', ''),
        }
    else:
        appinfo = {
            'latest_version_code': latest_app.get('latest_adr_version_code', ''),
            'latest_version_name': latest_app.get('latest_adr_version_name', ''),
            'latest_url': latest_app.get('latest_adr_url', ''),
        }

    return response(200, 'Get Latest App Success', u'获取最新版信息成功', {
        'appinfo': appinfo,
    })


def online_api(request):
    """ 是否上线 """
    platform = request.REQUEST.get('platform', '')
    channel = request.REQUEST.get('channel', '')
    version = request.REQUEST.get('version', '')

    app_settings = get_app_settings_info(platform, channel, version)

    return response(200, 'Get Online Status Success', u'获取是否上线成功', {
        'online': app_settings.get('online', True),
    })


@logit
def splash_api(request):
    """ 启动页面 """
    src = int(request.POST.get('src', 0))

    splashes = SplashInfo.objects.filter(src=src, status=True)
    splashes = [splash.data for splash in splashes]

    return response(200, 'Get Splash Success', u'获取最新版信息成功', {
        'splashes': splashes,
    })


@logit
def feedback_api(request):
    """ 用户反馈 """
    user_id = request.POST.get('user_id', '')
    feedback = request.POST.get('feedback', '')
    src = int(request.POST.get('src', 0))

    if not UserInfo.objects.filter(user_id=user_id).exists():
        return response(UserStatusCode.USER_NOT_FOUND)

    FeedbackInfo.objects.create(
        user_id=user_id,
        feedback=feedback,
        src=src,
    )

    return response(200, 'Feedback Success', u'反馈成功')


def download_api(request):
    """ 下载接口 """
    if request.weixin:
        return redirect(settings.DOWNLOAD_WX_URL)
    if request.iOS:
        return redirect(settings.DOWNLOAD_IOS_URL)
    return redirect(get_latest_app().get('latest_adr_url', ''))
