# coding=utf-8
from __future__ import print_function, unicode_literals, absolute_import
import six
import datetime
import json

from django.db import IntegrityError
from gm_types.gaia import CLIENT_TYPE

from rpc.decorators import bind_context
from api.tool.user_tool import get_user_from_context
from api.models.types import PLATFORM_CHOICES
from api.tool.log_tool import device_record_logger

from statistic.models import Device, DoctorDevice, SheQuDevice
from statistic.utils.idfv_tool import add_idfv


@bind_context('statistic/device/record')
def record_device(ctx, device_info={}):
    # 判断所需数据是否完整
    if device_info and device_info.get('platform', ''):
        device_id = device_info['device_id']
        from_app = device_info.get('from', '')

        if not device_id:
            device_record_logger.info("[No device_id] [{}] [{}]".format(
                datetime.date.strftime(datetime.date.today(), '%Y-%m-%d'), json.dumps(device_info)))
            return 'No device_id'

        try:
            if from_app not in CLIENT_TYPE:
                return 'no app name'

            mapper = {
                CLIENT_TYPE.USER: Device,
                CLIENT_TYPE.DOCTOR: DoctorDevice,
                CLIENT_TYPE.SHEQU: SheQuDevice,
            }
            m = mapper[from_app]
            idfv = device_info.get('idfv', '')
            platform = device_info.get('platform')

            device, created = add_idfv(m, platform, device_id)
            if created:
                # 只有第一次创建的时候，才设置频道
                device.channel = device_info['channel']
                device.created_time = datetime.datetime.now()
                # 设备创建时, 打印激活日志
                ctx.logger.app(is_activation=True)

        except IntegrityError:
            device_record_logger.info("[device exists] [{}] [{}]".format(
                datetime.date.strftime(datetime.date.today(), '%Y-%m-%d'), json.dumps(device_info))
            )
            return 'device exists'

        device.version = device_info['version']
        device.os_version = device_info['os_version']
        device.model = device_info['model']
        device.screen = device_info['screen']

        # 使用device_id更新安卓的idfv
        if device_info.get('platform').lower() == 'android' and not device.idfv:
            device.idfv = device_info.get('device_id')

        user = get_user_from_context(ctx)
        if user and from_app == CLIENT_TYPE.USER:
            try:
                device.user.add(user)
                result = 'new user'
            except IntegrityError:
                result = 'user exists'
        else:
            result = 'no user'

        device.save()

    else:
        device_record_logger.info("[data missing] [{}] [{}]".format(
            datetime.date.strftime(datetime.date.today(), '%Y-%m-%d'), json.dumps(device_info))
        )
        # 数据不完整
        result = ''

    return result


@bind_context('statistic/device/query_idfa_active_status')
def query_idfa_active_status(ctx, source, idfa_list):
    assert isinstance(source, six.string_types)

    ctx.logger.app(query_source=source)
    ctx.logger.app(idfa_list=idfa_list)

    active_idfa_list = Device.objects\
        .filter(platform=PLATFORM_CHOICES.IPHONE, device_id__in=idfa_list)\
        .values_list('device_id', flat=True)
    active_idfa_set = frozenset(active_idfa_list)

    ctx.logger.app(idfa_active_status_list=[
        1 if idfa in active_idfa_set else 0
        for idfa in idfa_list
    ])

    idfa_active_status_list = [
        idfa in active_idfa_set
        for idfa in idfa_list
    ]

    return {
        'idfa_active_status_list': idfa_active_status_list,
    }

@bind_context('statistic/device/idfa_active_status')
def get_idfa_active_status(ctx, idfa_list):

    ctx.logger.app(idfa_list=idfa_list)

    active_idfa_list = Device.objects\
        .filter(device_id__in=idfa_list)\
        .values_list('device_id', flat=True)

    active_idfa_set = frozenset(active_idfa_list)

    ctx.logger.app(idfa_active_status_list=[
        1 if idfa in active_idfa_set else 0
        for idfa in idfa_list
    ])

    idfa_active_status_list = [
        idfa in active_idfa_set
        for idfa in idfa_list
    ]

    return {
        'idfa_active_status_list': idfa_active_status_list,
    }

@bind_context('statistic/device/shequ_query_idfa_active_status')
def shequ_query_idfa_active_status(ctx, source, idfa_list):
    # for shequ client
    assert isinstance(source, six.string_types)

    ctx.logger.app(query_source=source)
    ctx.logger.app(idfa_list=idfa_list)

    active_idfa_list = SheQuDevice.objects.filter(
        platform=PLATFORM_CHOICES.IPHONE, device_id__in=idfa_list
    ).values_list('device_id', flat=True)
    active_idfa_set = frozenset(active_idfa_list)

    ctx.logger.app(idfa_active_status_list=[
        1 if idfa in active_idfa_set else 0
        for idfa in idfa_list
    ])

    idfa_active_status_list = [
        idfa in active_idfa_set
        for idfa in idfa_list
    ]

    return {
        'idfa_active_status_list': idfa_active_status_list,
    }

