from json import dumps
from typing import Dict, Tuple

from ._Action import Action
from ._Conditions import Conditions
from ._Exclusions import Exclusions


class Benefit(object):
    def __init__(self, raw_benefit):
        # type: (Dict) -> None

        self.id = raw_benefit.get("id")
        self.name = raw_benefit.get("name")
        self.user_description = raw_benefit.get("userDescription")
        self.priority = int(raw_benefit.get("priority")) if raw_benefit.get("priority") else None
        self.automatic = raw_benefit.get("automatic")
        self.tip_included = raw_benefit.get("tipIncluded") if raw_benefit.get("tipIncluded") else False
        self.ask_value = bool(raw_benefit.get("askValue"))
        conditions = raw_benefit.get("conditions") if raw_benefit.get("conditions") else {}
        self.conditions = Conditions(conditions)
        actions = [self._get_action(e) for e in raw_benefit.get("actions", {}).items()]
        self.actions = actions
        exclusions = raw_benefit.get("exclusions") if raw_benefit.get("exclusions") else {}
        self.exclusions = Exclusions(exclusions)
        self.raw = raw_benefit
        self.times_to_apply = raw_benefit.get("timesToApply")

    def to_json(self):
        # type: () -> str

        return dumps(self, default=lambda o: o.__dict__ if hasattr(o, '__dict__') else str(o), sort_keys=True)

    @staticmethod
    def _get_action(e):
        # type: (Tuple) -> Action

        return Action({"order": e[0], "name": e[1].items()[0][0], "value": e[1].items()[0][1]})
