# coding=utf-8

from django.conf import settings
from django.db import transaction

from gm_types.gaia import POINTS_TYPE, POINTS_OPERATION

from point.models import PointsInfo, Points


def get_points_deduction(points):
    return points / settings.POINTS_PER_YUAN


def deduction_to_points(deduction):
    deduction = int(deduction)
    return deduction * settings.POINTS_PER_YUAN


@transaction.atomic
def points_operate(
    user,
    num=0,
    operation=POINTS_OPERATION.ADD,
    reason=POINTS_TYPE.INVITE,
    link_user=None,
    link_topic=None,
    link_reply=None,
    link_topic_id=None,
    link_order_id=None, # for compatible
    is_new_sign_in=False
):

    if link_topic_id:
        from talos.models.topic import Problem
        link_topic = Problem.objects.get(id=link_topic_id)

    point_info = PointsInfo(user)
    number = point_info.points_operate(
        num=num, operation=operation, reason=reason, link_user=link_user,
        link_topic=link_topic, link_reply=link_reply, link_order_id=link_order_id,
        is_new_sign_in = is_new_sign_in
    )
    return number


def get_points_by_user_type(user, points_type, start_num=0, count=0):
    """
    通过类型获取该用户的积分
    """
    points = Points.objects.filter(user=user).filter(reason=points_type)
    result = [point for point in points[start_num:start_num + count]]
    return result
