# coding=utf-8
from api.models import UserBlackList, Doctor
from talos.models.live import LiveWhiteList
from talos.models.diary import DiaryCheck
from .transfer import MIN_TIME
from .es import tzlc
from api.tool.user_tool import filter_user_nick_name
from gm_types.gaia import DIARY_CONTENT_LEVEL


def get_2grams(s):
    if len(s) < 2:
        return [s]
    else:
        return [a + b for a, b in zip(s[0:-1], s[1:])]


def get_user(instance):
    # alias
    u = instance
    nickname = filter_user_nick_name(u)

    res = {
        'id': u.id,
        'last_name': nickname,
        'last_name_not_analyzed': nickname,
        'is_active': u.is_active,
        'membership_level': u.userextra.membership_level,
        'last_login': tzlc(u.userextra.last_login) or MIN_TIME,
    }

    if any([
        LiveWhiteList.objects.filter(user_id=u.id).exists(),
        DiaryCheck.objects.filter(
            diary__user_id=u.id,
            content_level=DIARY_CONTENT_LEVEL.EXCELLENT
        ).exists(),
    ]):
        res['last_name_2grams'] = get_2grams(nickname)
    else:
        res['last_name_2grams'] = None

    user_in_black_list = UserBlackList.objects.filter(bind_user=u).exists()
    user_is_doctor = Doctor.objects.filter(user=u).exists()

    if user_in_black_list or user_is_doctor:
        res['is_active'] = False

    return res
