#!/usr/bin/env python

from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, QTimer

import pygame
from pygame import mixer
import logging
import os

logger = logging.getLogger('players')


class PlayerError(Exception):
    pass


class PlayerSound(QObject):

    signalFinished = pyqtSignal()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__timer = QTimer(self)
        self.__timer.timeout.connect(self.__check)
        pygame.init()

    @pyqtSlot()
    def play(self, path):
        if not os.path.exists(path):
            raise PlayerError('File %s doesnt exist' % path)

        if mixer.music.get_busy():
            raise PlayerError('Still processing a file')

        logger.info('Starting new sound %s' % path)
        mixer.music.load(path)
        mixer.music.play()
        self.__timer.start(100)

    @pyqtSlot()
    def stop(self, block=False):
        mixer.music.stop()

    @property
    def is_busy(self):
        return mixer.music.get_busy()

    def __check(self):
        if not mixer.music.get_busy():
            self.__timer.stop()
            self.signalFinished.emit()
            logger.debug('Finished sound')
