import os
import webbrowser

from PyQt5 import QtWidgets
from PyQt5.QtGui import QIntValidator
from path import Path

from core import file_utilities
from core.models import Track
from core.repositories import TrackRepository
from ui.qt.dlg_meta_editor_ui import Ui_dlgMetaEditor


class DlgMetaEditor(QtWidgets.QDialog):
    def __init__(self, parent=None, track=None):
        super().__init__(parent)
        self.track = track
        self.createWidgets()

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

        self.ui.lineTitle.setText(self.track.title or "")
        self.ui.lineArtist.setText(self.track.artist or "")
        self.ui.lineAlbum.setText(self.track.album or "")
        self.ui.lineTrackNum.setText(str(self.track.track_num) if self.track.track_num is not None else "")

        self.ui.lineTrackNum.setValidator(QIntValidator())

        self.ui.lblPath.setText(Path(self.track.path).abspath())

        if self.track.status != Track.STATUS_UNAVAILABLE:
            self.ui.btnOpenTrackFolder.clicked.connect(self.openTrackFolder)
            self.ui.lblPath.setStyleSheet("")
        else:
            self.ui.btnOpenTrackFolder.setEnabled(False)
            self.ui.lblPath.setStyleSheet("QLabel { color : #cc0000; }")

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

    def openTrackFolder(self):
        folder = Path(self.track.path).parent
        file_utilities.open_file(folder)

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

    def ok(self):
        track_repo = TrackRepository()
        self.track.title = self.ui.lineTitle.text() or None
        self.track.artist = self.ui.lineArtist.text() or None
        self.track.album = self.ui.lineAlbum.text() or None
        num = self.ui.lineTrackNum.text()
        if num:
            self.track.track_num = int(num)
        track_repo.commit()
        self.done(1)

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