# coding=utf-8
from __future__ import absolute_import, unicode_literals
from gm_types.gaia import SLIDE_USER_TYPE, SLIDE_PAYMENT_TYPE


class UserTokenCollection(object):
    def __init__(self, level_dict=None):
        self.levels = level_dict if level_dict else UserTokenCollection.build_default_level()
        self.array = {}

    @classmethod
    def build_default_level(cls):
        level_dict = {
            (SLIDE_USER_TYPE.NEW_USER, SLIDE_PAYMENT_TYPE.NO_PAYMENT): {'ranking': 1, 'token': 1},
            (SLIDE_USER_TYPE.NEW_USER, SLIDE_PAYMENT_TYPE.HAVE_PAYMENT): {'ranking': 3, 'token': 1},
            (SLIDE_USER_TYPE.NEW_USER, SLIDE_PAYMENT_TYPE.ALL_PAYMENT): {'ranking': 3, 'token': 1},

            (SLIDE_USER_TYPE.OLD_USER, SLIDE_PAYMENT_TYPE.NO_PAYMENT): {'ranking': 2, 'token': 1},
            (SLIDE_USER_TYPE.OLD_USER, SLIDE_PAYMENT_TYPE.HAVE_PAYMENT): {'ranking': 5, 'token': 0},
            (SLIDE_USER_TYPE.OLD_USER, SLIDE_PAYMENT_TYPE.ALL_PAYMENT): {'ranking': 5, 'token': 0},

            (SLIDE_USER_TYPE.ALL_USER, SLIDE_PAYMENT_TYPE.NO_PAYMENT): {'ranking': 4, 'token': 1},
            (SLIDE_USER_TYPE.ALL_USER, SLIDE_PAYMENT_TYPE.HAVE_PAYMENT): {'ranking': 5, 'token': 0},
            (SLIDE_USER_TYPE.ALL_USER, SLIDE_PAYMENT_TYPE.ALL_PAYMENT): {'ranking': 5, 'token': 0},
        }
        return level_dict

    def add_element(self, ele):
        level_key = (ele.user_type, ele.payment_type)
        if level_key not in self.levels.keys():
            return
        if not self.array.get(level_key):
            self.array[level_key] = [ele]
        else:
            self.array[level_key].append(ele)

    def add_bulk(self, elements):
        [self.add_element(ele) for ele in elements]

    def get_result(self, level):
        if not isinstance(level, tuple):
            return []
        result = []
        for key, values in self.array.items():
            if key[0] in [level[0], SLIDE_USER_TYPE.ALL_USER] and key[1] in [level[1], SLIDE_PAYMENT_TYPE.ALL_PAYMENT]:
                data = {
                    'ranking': self.levels[key]['ranking'],
                    'token': self.levels[key]['token'],
                    'data': values
                }
                result.append(data)
        return result
