# encoding: utf-8
import time
from cStringIO import StringIO
from datetime import datetime
from xml.etree import cElementTree as eTree

from mw import MsgBusTableService as tableService
from old_helper import convert_from_utf_to_localtime
from utils import report_default_header, DATE_TIME_FMT, center, add_key_value_line, empty_line, add_table_line, \
    get_store_id, single_line_separator


class OpenedTablesReport(object):
    def __init__(self, table_repository, pos_id, operator_name_retriever):
        self.table_repository = table_repository
        self.pos_id = pos_id
        self.operator_name_retriever = operator_name_retriever
        self.store_id = get_store_id()

    def generate_opened_tables_report(self, pos_id):
        report = StringIO()
        title = "Relatorio Mesas Abertas"
        current_datetime = time.strftime(DATE_TIME_FMT)
        report.write(report_default_header(title, int(pos_id), None, None, current_datetime, self.store_id))
        self._opened_tables_report_body(report)

        return report.getvalue()

    def _opened_tables_report_body(self, report):
        tables = self.table_repository.get_opened_tables()

        columns_height = [18, 20]
        character_to_add = [".:", " ", " "]
        command = "Comanda"

        sectors_details = {}
        for table_id in tables:
            table_picture = tableService().get_table_picture(self.pos_id, str(table_id))
            table_picture_xml = eTree.XML(table_picture)
            table_orders = table_picture_xml.findall(".//Order")
            table_amount = sum([float(order.get("totalAmount")) for order in table_orders])
            date = datetime.strptime(table_picture_xml.get("startTS"), "%Y-%m-%d %H:%M:%S")
            date = convert_from_utf_to_localtime(date)
            operator_id = table_picture_xml.get("userId")
            operator_name = self.operator_name_retriever.get_operator_name(operator_id)
            seats = table_picture_xml.get("serviceSeats")

            columns = ["Total [Assentos]", 'R$ {:>8.2f}'.format(table_amount) + " [" + seats + "]"]
            is_tab = "TAB" in table_id
            table_context = "Comanda " if is_tab else "Mesa "

            table_name = table_picture_xml.get("name") if "name" in table_picture_xml.attrib else table_id
            table_properties = table_picture_xml.find("Properties")
            if table_properties is not None:
                table_name = table_properties.get("TAB_ID")[:7] if is_tab else table_name[:10]
            else:
                table_properties = table_picture_xml.find(".//OrderProperty[@key='TAB_ID']")
                table_name = table_properties.get("value")[:7] if is_tab else table_name[:10]

            table_detail_header = table_context + str(table_name) + " - " + datetime.strftime(date, "%d/%m/%Y %H:%M:%S")

            sector = command if is_tab else table_picture_xml.get("sector")
            table_info = dict(header=table_detail_header, operator=operator_name, columns=columns)
            if sector in sectors_details:
                sectors_details[sector].append(table_info)
            else:
                sectors_details[sector] = [table_info]

        sectors_keys = [s for s in sectors_details.keys() if s != command]
        sectors_keys.sort()
        if command in sectors_details.keys():
            sectors_keys.append(command)

        for sector in sectors_keys:
            report.write(center(sector.upper()))
            report.write(empty_line())
            for table_info in sectors_details[sector]:
                report.write(center(table_info["header"]))
                report.write(add_key_value_line("Operador........: ", table_info["operator"]))
                report.write(add_table_line(table_info["columns"], columns_height, character_to_add=character_to_add))
                report.write(empty_line())

            report.write(single_line_separator())
