import json
import logging

from application.repository.api import APIRepository
from dto import EndOfSaleNotesRequest
from nreports_api import NReports
from typing import (
    Dict,
    Optional,
)

logger = logging.getLogger(__name__)


class EndOfSaleNotesInteractor(object):

    def __init__(
        self,               # type: EndOfSaleNotesInteractor
        api_repository,     # type: APIRepository
        nreports_api,       # type: NReports
    ):
        # type: (...) -> None

        self.api_repository = api_repository
        self.nreports_api = nreports_api

    def execute(
        self,       # type: EndOfSaleNotesInteractor
        request,    # type: EndOfSaleNotesRequest
    ):
        # type: (...) -> Optional[Dict[str, str]]

        logger.info("Searching for end of sale notes. PosId/OrderId {}/{}".format(request.pos_id, request.order_id))
        response = self.api_repository.end_of_sale_notes(
            pos_id=request.pos_id,
            order_id=request.order_id,
        )

        logger.info("End of sale notes response: {}".format(response))
        if not response:
            return None

        parsed_data = self.nreports_api.request_report_json_parser(
            pos_id=None,
            report_json=json.dumps(response),
        )

        return parsed_data
