#! -*- coding: utf8 -*-
from __future__ import unicode_literals, absolute_import, print_function

import time

from gm_types.user_hierarchy import EventType

from .tasks import post_to_mima


class Event(object):

    __slots__ = ('user_id', 'item_id', 'initiator_id',)

    _is_sync = False
    event_type = None
    _is_toast = False
    toast_message = ''

    def __init__(self, user_id, item_id=None, initiator_id=None):
        """init an event.

        params:
            user_id: related to who
            item_id: topic id / diary id etc.
            initiator_id: who initiate this action(ops?)
        """
        self.user_id = user_id
        self.item_id = item_id
        self.initiator_id = initiator_id

    def _get_args(self):
        dt = {
            'event_type': self.event_type,
            'trigger_time': time.time(),
            'user_id': self.user_id,
            'item_id': self.item_id,
            # 'initiator_id': self.initiator_id,
        }

        extra_args = self.get_extra_args()
        if extra_args:
            dt.update(extra_args)
        return dt

    def get_extra_args(self):
        return {}

    def _send_to_mimas(self):
        """send request to mimas. check is_sync.
        """
        kwargs = self._get_args()

        if self._is_sync:
            result = post_to_mima(**kwargs)
            return {
                'status': 'finished',
                'value': result,
                'hint': '',
            }
        else:
            post_to_mima.delay(**kwargs)
            return {
                'status': 'pending',
                'value': None,
                'hint': '',
            }

    def validate(self):
        """check msg is valid."""
        pass

    def emit(self):
        """notify mimas system.

        return:
            {
                'growth_message': '',
                'value': None,  # added growth value
            }
        """
        result = self._send_to_mimas()
        if result['status'] == 'finished':
            return {
                'growth_message': self.build_toast_message(result['value']),
                'value': result['value'],
            }

        return {
            'growth_message': '',
            'value': None,
        }

    def build_toast_message(self, value):
        if self._is_toast and self.toast_message and value:
            return self.toast_message.format(value)
        return ''


class AddPortraitEvent(Event):
    event_type = EventType.COMPLETEPORTRAIT


class BindPhoneEvent(Event):
    event_type = EventType.BINDPHONE


class CreateOperationTopicEvent(Event):
    _is_sync = True
    event_type = EventType.CREATEOPERATIONTOPIC
    _is_toast = True
    toast_message = '+{}成长值'


class CreateNoneOperationTopicEvent(Event):
    _is_sync = True
    event_type = EventType.CREATENONOPERATIONTOPIC
    _is_toast = True
    toast_message = '+{}成长值'


class CommentDiaryEvent(Event):
    _is_sync = False
    event_type = EventType.COMMENTDIARY
    _is_toast = True    # 前端暂时只toast'评论成功'， 不需要同步
    toast_message = '+{}成长值'

    # def build_toast_message(self, value):
    #     # 前端暂时toast不包含value都message ，暂时注释
    #     # if value > 0:
    #     #     return self.toast_message.format(value)
    #     return u'回复成功'


class CommentTopicEvent(Event):
    _is_sync = False  # 前端暂时只toast'评论成功'， 不需要同步
    event_type = EventType.COMMENTTOPIC
    _is_toast = True
    toast_message = '评论成功，+{}成长值'

    def build_toast_message(self, value):
        # 前端暂时toast不包含value都message ，暂时注释
        # if value > 0:
        #     return self.toast_message.format(value)
        return u'评论成功'


class DiaryCommentedEvent(Event):
    event_type = EventType.DIARYCOMMENTED


class TopicCommentedEvent(Event):
    event_type = EventType.TOPICCOMMENTED


class OpDiaryBeExFromFine(Event):
    event_type = EventType.OPERATIONDIARYBEEDEXCELENTFROMFINE


class NonOpDiaryBeExFromFine(Event):
    event_type = EventType.NONOPERATIONDIARYBEEXCELENTFROMFINE


class OpDiaryBeExFromOther(Event):
    event_type = EventType.OPERATIONDIARYBEEDEXCELENTFROMOTHER


class NonOpDiaryBeExFromOther(Event):
    event_type = EventType.NONOPERATIONDIARYBEEXCELENTFROMOTHER


class OpDiaryBeFineFromEx(Event):
    event_type = EventType.OPERATIONDIARYBEFINEFROMEX


class NonOpDiaryBeFineFromEx(Event):
    event_type = EventType.NONOPERATIONDIARYBEFINEFROMEX


class OpDiaryBeFineFromOther(Event):
    event_type = EventType.OPERATIONDIARYBEFINEFROMOTHER


class NonOpDiaryBeFineFromOther(Event):
    event_type = EventType.NONOPERATIONDIARYBEFINEFROMOTHER


class AnswerBeRecommendedEvent(Event):
    event_type = EventType.ANSWERRECOMMENDED


class QuestionBeRecommendEvent(Event):
    event_type = EventType.QUESTIONRECOMMENDED


class TopicIsSpamEvent(Event):
    event_type = EventType.TOPICISSPAM


class CommentIsSpamEvent(Event):
    event_type = EventType.COMMENTISSPAM


class BuyServiceEvent(Event):

    __slots__ = ('user_id', 'item_id', 'initiator_id', 'pre_payment',)

    event_type = EventType.BUYSERVICE

    def __init__(self, user_id, item_id=None, initiator_id=None, pre_payment=None):
        """init an event.

        params:
            user_id: related to who
            item_id: topic id / diary id etc.
            initiator_id: who initiate this action(ops?)
            pre_payment: service pre payment
        """
        super(BuyServiceEvent, self).__init__(user_id, item_id, initiator_id)
        self.pre_payment = pre_payment

    def get_extra_args(self):
        return {'pre_payment': self.pre_payment}


class CheckinEvent(Event):
    _is_sync = True
    event_type = EventType.CHECKIN
