"""Definition of the final biseau context viewer"""
import clyngor
import biseau as bs
from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtGui import *


class ModelsViewer(QWidget):
    """A view on the ASP models generated by biseau,
    able to transmit dot to another widget
    """

    def __init__(self, dot_viewer):
        super().__init__()
        self.setWindowTitle("Models")
        self.multishot_mode = False

        self._dot_viewer = dot_viewer
        self.tool_bar = QToolBar()
        self.tool_bar.addAction('Compile to dot', lambda: self.set_models(self.__models))
        self.edit = QTextEdit()
        self.edit.setFont('Monospace')
        self.edit.setReadOnly(True)  # TODO: enable editions and subsequent feed-forward
        _layout = QVBoxLayout()
        _layout.addWidget(self.tool_bar)
        _layout.addWidget(self.edit)
        _layout.setContentsMargins(0, 0, 0, 0)
        self.__models = []
        self.set_models([])
        self.setLayout(_layout)

    def _setup_toolbar(self):
        "Populate the toolbar"

    def _make_text(self):
        for idx, model in enumerate(self.__models, start=1):
            yield f'Model {idx}:'
            yield clyngor.utils.answer_set_to_str(model, atom_end='', atom_sep=' ')

    def _make_models(self):
        for model in self.__models:
            yield clyngor.utils.answer_set_to_str(model, atom_end='.', atom_sep='\n')

    def set_models(self, models:iter, compile_and_send=True):
        self.__models = tuple(models)
        text = '\n'.join(self._make_text())
        self.edit.setText(text)
        if compile_and_send:
            if self.multishot_mode:
                dots = map(''.join, bs.compile_contexts_to_dots(self._make_models()))
                self._dot_viewer.set_dots(dots)
            else:
                dot = bs.compile_contexts_to_dot(self._make_models())
                self._dot_viewer.set_dot(dot)

    def get_models(self):
        return self.edit.toPlainText()
