#! /usr/bin/env python
# -*- coding: utf-8 -*-
import json

from api.models.face.user_record import ScanRecord

from rpc.decorators import bind_context, bind
from api.tool.user_tool import get_user_from_context
from gm_types.gaia import SCAN_TYPE
from api.services.user_face_services import FaceService
from api.tasks.face_task import rectify_client_record_task


@bind_context('api/scan_record/have_scan_face_and_skin', with_context=True)
def have_scan_face_and_skin(ctx, device_id):
    result = {}
    user = get_user_from_context(ctx)
    if user:
        have_scan_face = ScanRecord.objects.filter(user_id=user.id).last()
    else:
        have_scan_face = ScanRecord.objects.filter(device_id=device_id).last()
    result['have_scan_face'] = True if have_scan_face else False
    return result


@bind('api/scan_record/save_scan_face_record')
def save_user_scan_face_record(user_id, device_id, data, scan_type=SCAN_TYPE.SCAN_FACE):
    ScanRecord.objects.create(user_id=user_id, device_id=device_id, scan_type=scan_type, data=data)


@bind_context('api/scan_record/get_scan_face_record')
def get_scan_face_record(ctx, device_id):
    user = get_user_from_context(ctx)
    if user:
        obj = ScanRecord.objects.filter(user_id=user.id, scan_type=SCAN_TYPE.SCAN_FACE).last()
    else:
        obj = ScanRecord.objects.filter(device_id=device_id, scan_type=SCAN_TYPE.SCAN_FACE).last()
    data = obj.data if obj else {}
    return {"data": data}


@bind_context('api/had_test_record')
def get_scan_face_record(ctx, device_id):
    user = get_user_from_context(ctx)
    user_id = user.id if user else None

    return FaceService.had_test_record(user_id=user_id, device_id=device_id)


@bind_context('api/rectify_client_record')
def rectify_client_record(ctx, device_id):
    user = get_user_from_context(ctx)
    user_id = user.id if user else None

    return rectify_client_record_task(user_id=user_id, device_id=device_id)
