import os
from pathlib import Path
from functools import partial

from PyQt5.QtCore import Qt, QSize
from PyQt5.QtWidgets import QLabel, QPushButton, QVBoxLayout, QSizePolicy

root_dir = Path(__file__).parent.parent
root_dir = str(root_dir)

css_screens = {
    'small': 'flat_button_small.css',
    'medium': 'flat_button_medium.css',
    'large': 'flat_button_large.css'
}

__all__ = ['CustomButton']


class CustomButton(QPushButton):

    def __init__(self, parent, id, size='small', icon=None, title=None,
        desc_extractor=None, method=None, record=None,
        name_style='standard_button'):
        """
            Create custom, responsive and nice button flat style,
            with two subsections
                 _ _ _ _ _
                |  ICON   |   -> Title / Icon (Up section)
                |  DESC   |   -> Descriptor section (Optional - bottom section)
                |_ _ _ _ _|

            :id :: Id of button,
            :icon:: A QSvgRenderer object,
            :title :: Name of button,
            :descriptor:: Text name or descriptor of button,
            :method:: Method for connect to clicked signal if it missing '*_pressed'
                will be used instead.
            :Record:: Record linked to button
            :name_style:: define which type of button style must be rendered.
        """
        super(CustomButton, self).__init__()
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        if hasattr(parent, 'screen_size'):
            size = parent.screen_size

        if name_style == 'mini_button':
            _size = 70
            qsize = QSize(30, 30)
            self.setMaximumHeight(_size)
        elif size == 'small' or name_style == 'toolbar':
            qsize = QSize(35, 35)
        else:
            qsize = QSize(50, 50)

        self.id = id
        styles = []

        css_file = os.path.join(root_dir, 'css', css_screens[size])
        with open(css_file, 'r') as infile:
            styles.append(infile.read())

        self.setStyleSheet(''.join(styles))
        self.setObjectName(name_style)
        rows = []
        if icon:
            pixmap = icon.pixmap(qsize)
            label_icon = QLabel()
            label_icon.setObjectName('label_icon')
            label_icon.setPixmap(pixmap)
            label_icon.setAlignment(Qt.AlignCenter | Qt.AlignCenter)
            rows.append(label_icon)

        if title:
            rows.append(self.get_label(title))

        if desc_extractor:
            desc = record.get(desc_extractor)
            if not desc:
                desc = record.get('rec_name')
            rows.append(self.get_label(desc))

        if len(rows) >= 1:
            vbox = QVBoxLayout()
            for w in rows:
                vbox.addWidget(w, 1)
            self.setLayout(vbox)

        method = getattr(parent, method)
        if method and record:
            method = partial(method, record)
        self.clicked.connect(method)

    def get_label(self, name):
        label_title = QLabel(name)
        label_title.setWordWrap(True)
        label_title.setAlignment(Qt.AlignCenter | Qt.AlignCenter)
        label_title.setObjectName('label_custom_button')
        return label_title
