from json import loads, dumps

from typing import List, Dict

from . import Benefit


class OrderBenefitInfo(object):
    def __init__(self, benefit, used_discount_ids, added_sale_lines, burnt_items, promotion_tender,
                 discount_item_values, order_state=None, benefit_applied=False, benefit_key=None, times_to_apply=None):
        # type: (Dict, list[int], list[int], Dict, List, Dict, str, bool, str, int) -> None

        self.benefit = Benefit(benefit)
        self.used_discount_ids = used_discount_ids
        self.added_sale_lines = added_sale_lines
        self.burnt_items = burnt_items
        self.order_state = order_state
        self.promotion_tender = promotion_tender
        self.discount_item_values = discount_item_values
        self.benefit_applied = benefit_applied
        self.benefit_key = benefit_key
        self.times_to_apply = times_to_apply

    @staticmethod
    def from_json(json):
        benefit = json.get("benefit", "{}")
        used_discount_ids = json.get("used_discount_ids", [])
        added_sale_lines = json.get("added_sale_lines", [])
        burnt_items = json.get("burnt_items", {})
        order_state = json.get("order_state")
        item_values = json.get("discount_item_values", {})
        tenders = json.get("promotion_tender", [])
        benefit_applied = json.get("benefit_applied", [])
        benefit_key = json.get("benefit_key", None)
        times_to_apply = json.get("times_to_apply", None)

        return OrderBenefitInfo(benefit, used_discount_ids, added_sale_lines, burnt_items, tenders, item_values,
                                order_state, benefit_applied, benefit_key, times_to_apply)

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

        return dumps({
            "benefit": loads(self.benefit.to_json()),
            "used_discount_ids": list(self.used_discount_ids),
            "added_sale_lines": list(self.added_sale_lines),
            "burnt_items": self.burnt_items if self.benefit.conditions.burn_items else dict(),
            "order_state": self.order_state,
            "promotion_tender": self.promotion_tender,
            "discount_item_values": self.discount_item_values,
            "times_to_apply": self.times_to_apply
        })
