import os
from PyQt5.QtWidgets import (
    QWidget, QGridLayout, QPushButton, QVBoxLayout
)

DIR_SHARE = os.path.abspath(
    os.path.normpath(os.path.join(__file__, '..', '..', 'share')))

__all__ = ['ManageTables', 'MixButton']

STATES = {
    'available': 'rgb(195, 195, 195)',
    'occupied': 'rgb(255, 210, 30)',
    'reserved': 'rgba(80, 190, 220, 0.8)'
}

button_style = """
    min-height: 40px;
    min-width: 100px;
"""

button_style_1 = """
    font: bold 30px;
    min-width: 100px;
    text-align: center;
"""


class MixButton(QWidget):
    def __init__(self, value, activate_method, see_sale_method):
        super(MixButton, self).__init__()
        self.name = value['name']
        self.table_id = value['id']
        self.set_data(value)
        layout = QVBoxLayout()
        self.activate_method = activate_method
        self.see_sale_method = see_sale_method
        table_name = 'MESA ' + str(value['name'])
        button1 = QPushButton(table_name)
        button1.clicked.connect(self.handle_activate)
        button1.setStyleSheet(button_style_1)
        button2 = QPushButton('VER MESA')
        button2.clicked.connect(self.handle_see_sale)
        button2.setStyleSheet(button_style)
        layout.addWidget(button1)
        layout.addWidget(button2)
        self.setLayout(layout)
        self.show()

    def handle_activate(self):
        if self.state == 'available':
            state = 'occupied'
        else:
            state = 'available'

        values = {
            'id': self.table_id,
            'sale_id': self.sale_id,
            'state': self.state,
        }
        res = self.activate_method(values, self.name, state)
        if res:
            self.set_data(res)

    def handle_see_sale(self):
        self.see_sale_method(self.table_id)

    def set_data(self, record):
        self.state = record['state']
        self.sale_id = record['sale']
        color = STATES[self.state]
        new_style_ = f"""
            min-height: 100px;
            min-width: 100px;
            background-color: {color};
        """
        self.setStyleSheet(new_style_)


class ManageTables(QGridLayout):

    def __init__(self, parent, tables, activate_method, see_sale_method):
        super(ManageTables, self).__init__()
        self.setHorizontalSpacing(1)
        self.setVerticalSpacing(1)
        columns = 6
        rows = int(len(tables) / columns) + 1
        self.buttons = {}
        positions = [(i, j) for i in range(rows) for j in range(columns)]
        for position, value in zip(positions, tables):
            button = MixButton(value, activate_method, see_sale_method)
            self.buttons[button.table_id] = button
            self.addWidget(button, *position)

    def update_records(self, records):
        for rec in records:
            button = self.buttons[rec['id']]
            button.set_data(rec)
