from path import Path

from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem, QFileDialog, QMessageBox

from core.file_utilities import is_subdir_of
from core.models import MusicFolder
from core.repositories import MusicFolderRepository


class MusicFoldersTable(QTableWidget):
    music_folder_statuses = [
        ('Inconnu', ':/img/rsc/unknown.png'),
        ('Valide', ':/img/rsc/valid.png'),
        ('Inaccessible', ':/img/rsc/invalid.png')
    ]

    def populate(self):
        self.hideColumn(0)

        music_folders = MusicFolderRepository().get_all()
        self.clear()

        row = 0

        for music_folder in music_folders:
            self.insertRow(row)
            item = QTableWidgetItem()
            item.setData(0, music_folder.id)
            self.setItem(row, 0, item)

            status_lbl, status_pic = self.music_folder_statuses[music_folder.status]
            self.setItem(row, 1, QTableWidgetItem(QIcon(status_pic), status_lbl))

            self.setItem(row, 2, QTableWidgetItem(music_folder.path))
            row += 1

    def selected_music_folder(self):
        music_folder_id = self.item(self.currentRow(), 0).data(0)
        if not music_folder_id:
            return None
        return MusicFolderRepository().get_by_id(int(music_folder_id))

    def add_music_folder(self):
        path = QFileDialog.getExistingDirectory(self, "Sélectionnez le dossier à ajouter")
        if not path:
            return

        path = Path(path)

        repo = MusicFolderRepository()
        if repo.exists("path", str(path)):
            QMessageBox.warning(self, "Ajout invalide",  "Ce dossier a déjà été ajouté")
            return

        folder = MusicFolder(path=path)
        repo.create(folder, True)
        self.populate()

    def remove_music_folder(self):

        music_folder = self.selected_music_folder()
        if music_folder is None:
            return

        if QMessageBox.question(
            self,
            "Confirmer",
            "Êtes-vous sûr(e) de vouloir supprimer ce dossier de la liste des dossiers à analyser?"
        ) != QMessageBox.Yes:
            return

        repo = MusicFolderRepository()
        repo.delete(music_folder, True)
        self.populate()
