# coding:utf-8
from __future__ import absolute_import, unicode_literals

from rpc.decorators import bind_context, bind
from api.models import UserHomePage
from api.tool.user_tool import get_user_from_context
from django.db import transaction
from gm_types.gaia import WRONG_DEVICE_ID
from statistic.models import Device
import datetime
from api.tool.log_tool import logging_exception
from gaia.base import INDEX_V4_USER_GREY_NUM


@bind_context('api/index_v4_new/get_home_type')
def get_user_home_page(ctx):
    current_user = get_user_from_context(ctx)

    try:
        home_page_type = UserHomePage.objects.get(user=current_user).home_page

    except UserHomePage.DoesNotExist:
        home_page_type = 0

    return {'type': home_page_type}


@bind_context('api/index_v4_new/set_home_type')
def set_home_page(ctx, home_page_type):
    current_user = get_user_from_context(ctx)
    with transaction.atomic():
        home_page, created = UserHomePage.objects.update_or_create(user=current_user, defaults={'home_page': home_page_type})
        home_page.save()
    return {
        'data': 'ok'
    }


@bind_context('api/index_v4_new/home_type')
def get_app_home_page(ctx, device_id, start_num):
    result = {'type': 0}
    result['is_oddeven'] = gray_hit(device_id)
    result['is_newuser'] = is_new_user(device_id, start_num)
    current_user = get_user_from_context(ctx)
    if current_user:
        try:
            home_page = UserHomePage.objects.get(user=current_user).home_page
            result['type'] = home_page
            return result
        except UserHomePage.DoesNotExist:
            pass
        except:
            logging_exception()

    if device_id not in WRONG_DEVICE_ID and gray_hit(device_id):
        result['type'] = 1
    return result


def gray_hit(divice_id):
    """是否命中灰度
    device_id最后一位转ascii码的个位上的数在配置数中的命中
    """
    if str(divice_id[-1]) in INDEX_V4_USER_GREY_NUM:
        return True
    return False


def is_new_user(device_id, start_num):
    result = False
    if start_num <= 5:
        days_ago = datetime.datetime.now() - datetime.timedelta(days=30)
        try:
            device = Device.objects.filter(device_id=device_id).last()
            if not device or device and device.created_time > days_ago:
                result = True

        except:
            logging_exception()
    return result
