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

import os

from django.conf import settings
from django.shortcuts import redirect
from django_logit import logit
from django_response import response

from account.models import UserInfo
from operation.models import FeedbackInfo, GuestEntranceControlInfo, LatestAppInfo, SplashInfo
from utils.error.errno_utils import UserStatusCode
from utils.redis.rapp import get_latest_app
from utils.redis.rguest import get_guest_entrance_control
from utils.redis.roperation.rbox_program_version import get_box_program_version
from utils.redis.rpatch import get_app_patch_info
from utils.redis.rsettings import get_app_settings_info
from utils.version_utils import is_version_match


@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,
    })


@logit
def patch_api(request):
    """ APP 补丁 """
    platform = request.GET.get('platform', '') or request.POST.get('platform', '')
    version = request.GET.get('version', '') or request.POST.get('version', '')
    src = int(request.POST.get('src', 0))

    patch_info = get_app_patch_info(platform, version, src)

    return response(200, 'Get Patch Info Success', u'获取补丁信息成功', {
        'patch_url': patch_info.get('patch_url', ''),
    })


@logit
def online_api(request):
    """ 是否上线 """
    platform = request.GET.get('platform', '') or request.POST.get('platform', '')
    channel = request.GET.get('channel', '') or request.POST.get('channel', '')
    version = request.GET.get('version', '') or request.POST.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 guest_api(request):
    """ 游客状态 """
    src = int(request.POST.get('src', 0))

    gen = get_guest_entrance_control(src)

    # 是否配置游客入口控制信息
    if not gen:
        return response(UserStatusCode.GUEST_NOT_ALLOWED)

    # 平台校验
    platform = gen.get('platform', '')
    if request.Android:
        if platform not in [GuestEntranceControlInfo.ADR, GuestEntranceControlInfo.BOTH]:
            return response(UserStatusCode.GUEST_NOT_ALLOWED)
    else:
        if platform not in [GuestEntranceControlInfo.IOS, GuestEntranceControlInfo.BOTH]:
            return response(UserStatusCode.GUEST_NOT_ALLOWED)

    # 版本校验
    if not is_version_match(request, gen):
        return response(UserStatusCode.GUEST_NOT_ALLOWED)

    return response(200, 'Guest Login Allowed', u'游客登录开启')


@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, status=True).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):
    """ 下载接口 """
    src = int(request.GET.get('src', 0))

    if request.weixin:
        if src == LatestAppInfo.PAIAI_USER:
            wx_url = settings.PAI2_USER_DOWNLOAD_WX_URL
        elif src == LatestAppInfo.PAIAI_LENSMAN:
            wx_url = settings.PAI2_LENSMAN_DOWNLOAD_WX_URL
        elif src == LatestAppInfo.PAIAI_TOURGUIDE:
            wx_url = settings.PAI2_TOURGUIDE_DOWNLOAD_WX_URL
        return redirect(wx_url)

    if request.iOS:
        if src == LatestAppInfo.PAIAI_USER:
            ios_url = settings.PAI2_USER_DOWNLOAD_IOS_URL
        elif src == LatestAppInfo.PAIAI_LENSMAN:
            ios_url = settings.PAI2_LENSMAN_DOWNLOAD_IOS_URL
        elif src == LatestAppInfo.PAIAI_TOURGUIDE:
            ios_url = settings.PAI2_TOURGUIDE_DOWNLOAD_IOS_URL
        return redirect(ios_url)

    return redirect(get_latest_app(src).get('latest_adr_url', ''))


def kvformat(bpversion, k):
    v = bpversion.get(k, '')
    return '"{}":{}'.format(k, v) if isinstance(v, int) else '"{}":"{}"'.format(k, v)


def box_program_version_api(request):
    """ BOX 程序版本信息 """
    bpversion = get_box_program_version()

    keys = ['srv_version_code', 'srv_version_name', 'srv_sha1', 'proc_version_code', 'proc_version_name', 'proc_sha1']
    kvs = [kvformat(bpversion, k) for k in keys]
    bpversion_str = os.linesep.join(kvs)

    return response(200, 'Get Box Program Version Success', u'获取盒子程序版本成功', {
        'bpversion': bpversion,
        'bpversion_str': bpversion_str,
    })
