# coding: utf-8
from gm_types.gaia import PLATFORM_CHOICES

from rpc.decorators import bind_context, bind
from api.models import DeviceBinding
from api.tool.user_tool import get_user_from_context

from statistic.models import Device


@bind_context('api/device_binding/update')
def update_device_binding(ctx, device_id):

    """

    :param ctx:
    :param device_id:
    :return:
    """
    user = get_user_from_context(ctx)
    if not (user and device_id):
        return False

    city = user.userextra.city
    province = city.province if city else None
    DeviceBinding.objects.update_or_create(user=user, defaults={
        'device': device_id, 'city': city, 'province': province
    })


@bind('api/device/is_doctor_device')
def is_doctor_device(device_id):
    """

    :param device_id:
    :return:
    """
    if not device_id:
        return False
    try:
        device = Device.objects.get(device_id=device_id)
    except (Device.DoesNotExist, Device.MultipleObjectsReturned):
        return False

    return device.user.filter(doctor__isnull=False).exists()


@bind('api/device/user_app_version')
def get_device_app_version_by_user_id(user_id):
    """通过用户ID获取最近使用的客户端app版本号

    :param: user_id: 用户ID
    :return: version string 版本号
    """
    # TODO: add 5 min cache
    try:
        device = Device.objects.only('version', 'last_activity').filter(
            user__id=user_id, platform__in=[PLATFORM_CHOICES.ANDROID, PLATFORM_CHOICES.IPHONE]
        ).order_by('-last_activity').first()
    except:
        return "0.0.0"
    return device.version if device and device.version else '0.0.0'
