from datetime import datetime

from PyQt5 import QtWidgets

from core.models import Session
from core.repositories import SessionRepository
from ui.qt.dlg_playlist_ui import Ui_dlgPlaylist


class DlgPlaylist(QtWidgets.QDialog):
    def __init__(self, playlist=None, parent=None):
        super().__init__(parent)

        self.playlist = playlist if playlist is not None else Session()
        self.date_enabled = False
        self.createWidgets()

    def createWidgets(self):
        self.ui = Ui_dlgPlaylist()
        self.ui.setupUi(self)

        if self.playlist.name:
            self.ui.lineName.setText(self.playlist.name)

        if self.playlist.date:
            self.ui.lineDate.setDateTime(self.playlist.date)
            self.toggleDateActivation()
        else:
            self.ui.lineDate.setDateTime(datetime.now())

        self.ui.textNotes.setText(self.playlist.notes or "")

        self.ui.chkDateEnabled.stateChanged.connect(self.toggleDateActivation)

        self.ui.btnSave.clicked.connect(self.save)
        self.ui.btnCancel.clicked.connect(self.cancel)

    def toggleDateActivation(self):
        new_state = not self.date_enabled
        self.ui.lineDate.setEnabled(new_state)
        self.ui.chkDateEnabled.setChecked(new_state)
        self.date_enabled = new_state

    @classmethod
    def edit(cls, parent, playlist=None):
        dlg = cls(playlist, parent)
        r = dlg.exec_()
        return r

    def cancel(self):
        self.done(0)

    def save(self):
        self.playlist.name = self.ui.lineName.text()
        self.playlist.date = self.ui.lineDate.dateTime().toPyDateTime() if self.date_enabled else None
        self.playlist.notes = self.ui.textNotes.toPlainText()

        repo = SessionRepository()
        if not self.playlist.id:
            repo.create(self.playlist)
        repo.commit()
        self.done(1)



