# encoding: utf-8
from benefitsreport import BenefitsReport
from report import Generator
from reportsdata.benefitsreport.dto import BenefitsGeneratorDto, BenefitsHeaderDto, BenefitsBodyDto


class BenefitsGenerator(Generator):
    def __init__(self, order_repository, initial_date, end_date, operator_id, benefits):

        self.order_repository = order_repository
        self.initial_date = initial_date
        self.end_date = end_date
        self.operator_id = operator_id
        self.benefits = benefits

    def generate_data(self):
        # type: (...) -> BenefitsGeneratorDto

        benefits_report = BenefitsReport(self.order_repository)
        if self.benefits and self.benefits[0].get("id") is not None:
            generator_dto = self.detailed_report(benefits_report)
        else:
            generator_dto = self.consolidated_report(benefits_report)

        return generator_dto

    def detailed_report(self, benefits_report):
        # type: (BenefitsReport) -> BenefitsGeneratorDto

        orders = benefits_report.get_benefits_orders_detailed(
                self.initial_date,
                self.end_date,
                self.operator_id,
                self.benefits
        )
        promotion_name = self.benefits[0].get("name").encode("utf8")
        title = "$BENEFIT_REPORT_DETAILED"
        header = BenefitsHeaderDto(title, promotion_name, self.operator_id, self.initial_date, self.end_date)
        body = BenefitsBodyDto(orders, "detailed")

        return BenefitsGeneratorDto(header, body)

    def consolidated_report(self, benefits_report):
        # type: (BenefitsReport) -> BenefitsGeneratorDto

        orders = benefits_report.get_benefits_orders_consolidated(self.initial_date,
                                                                  self.end_date,
                                                                  self.operator_id)
        promotion_name = "$ALL"
        title = "$BENEFIT_REPORT_CONSOLIDATED"
        header = BenefitsHeaderDto(title, promotion_name, self.operator_id, self.initial_date, self.end_date)
        body = BenefitsBodyDto(orders, "consolidated")

        return BenefitsGeneratorDto(header, body)
