"""Join Podcast (Call menu): a conference room joined with its audio in stereo over WebRTC (never SIP), its chat
over MSRP, video only when asked for (the camera off otherwise, to be turned on in the room).

- PodcastWatcher follows the podcast from its start until it really ends: then the audio goes back to the system
  default devices, and Do Not Disturb (chosen in the dialog: incoming calls rejected while on air) ends.
  Really ends: left here (Leave, Hang Up, AG CuteMusic's HANG UP: the room's reason 'left'), or, when the room
  ended by itself (the server, the network), no redial of it within REDIAL_GRACE, or AG Podcast Mixer gone
  meanwhile (the mixer powered down, AG CuteMusic quit). A rejoin attaches to the same podcast: the devices and
  Do Not Disturb stay as they are.
- The last podcast is kept as it was joined (account, room, video, videos, Do Not Disturb): AG CuteMusic's REDIAL
  rejoins it exactly so while no call was made after it.
"""

from PyQt6.QtCore import QObject, QTimer
from PyQt6.QtWidgets import QApplication

from sipsimple.account import BonjourAccount
from sipsimple.application import SIPApplication
from sipsimple.configuration.settings import SIPSimpleSettings

from blink.logging import ActivityLog


__all__ = ['Podcast', 'PodcastWatcher', 'remember', 'last_podcast', 'last_podcast_any', 'podcast_for', 'rejoin', 'select_mixer', 'mixer_present', 'on_air', 'started']


class Podcast(object):
    """A podcast as it was joined from the Join Podcast dialog."""

    def __init__(self, account, conference_uri, target, video, sources, do_not_disturb):
        self.account = account
        self.conference_uri = conference_uri
        self.target = target                # the RoomTarget of a room of another SylkServer, or None
        self.video = video
        self.sources = sources              # (camera or None, screen or None, [(source, label)])
        self.do_not_disturb = do_not_disturb
        self.redial_mark = None             # the last call dialed when it was joined: it is the redial target while that stays so


_last = None


def remember(podcast):
    global _last
    from blink.sessions import SessionManager
    podcast.redial_mark = SessionManager().last_dialed_uri
    _last = podcast


def last_podcast():
    """The last podcast, when no call was dialed after it (it is what REDIAL redials), else None."""
    if _last is None:
        return None
    from blink.sessions import SessionManager
    return _last if SessionManager().last_dialed_uri is _last.redial_mark else None


def last_podcast_any():
    """The last podcast joined, a call made after it or not."""
    return _last


def podcast_for(address):
    """The last podcast, when address (user@domain, a SIP URI, "Name <uri>") is its room (or the room it was in)."""
    if _last is None or not address:
        return None

    def bare(text):
        text = str(text).strip()
        if '<' in text and '>' in text:
            text = text[text.index('<') + 1:text.index('>')]
        text = text.split(';', 1)[0].lower()
        for prefix in ('sip:', 'sips:'):
            if text.startswith(prefix):
                text = text[len(prefix):]
        return text if '@' in text else None

    wanted = bare(address)
    rooms = {bare(_last.conference_uri)}
    watcher = PodcastWatcher.current
    if watcher is not None and watcher.room:
        rooms.add(bare(watcher.room))
    return _last if wanted is not None and wanted in rooms else None


def rejoin(podcast):
    """The podcast again, exactly as it was started: the same account, the dialog's choices, AG Podcast Mixer as the input again."""
    ActivityLog().info(f'[conference] Rejoining the podcast {podcast.conference_uri} as it was started')
    main_window = getattr(QApplication.instance(), 'main_window', None)
    if main_window is not None:
        main_window.podcast_dialog.rejoin(podcast)


def mixer_present():
    from blink import cutemusic
    try:
        return cutemusic.DEVICE in SIPApplication.engine.input_devices
    except Exception:
        return False


def select_mixer():
    """AG Podcast Mixer as the input when it is listed (AG CuteMusic's mixer on); the output left as it is (the mixer
    is an input only). Only once joining: the dialog alone (or Cancel) changes no device."""
    from blink import cutemusic
    if not mixer_present():
        return
    settings = SIPSimpleSettings()
    if settings.audio.input_device != cutemusic.DEVICE:
        ActivityLog().info(f'[conference] Join Podcast: {cutemusic.DEVICE} selected as the input')
        settings.audio.input_device = cutemusic.DEVICE
        settings.save()


def on_air(account):
    """Whether incoming calls to account are refused: Do Not Disturb while on air in a podcast."""
    watcher = PodcastWatcher.current
    return watcher is not None and watcher.do_not_disturb and account is not None and watcher.account is account


def started(video_room, account, do_not_disturb):
    """A podcast joined (video_room, a VideoroomSession): a rejoin while the last one waits for it goes on with it."""
    watcher = PodcastWatcher.current
    if watcher is not None and watcher.waiting:
        watcher.attach(video_room)
    else:
        if watcher is not None:
            watcher.finish('another podcast started', keep_devices=True)
        PodcastWatcher(video_room, account, do_not_disturb)


def _show_on_air(on_air):
    """The main window's state: Busy, "Do Not Disturb: on air", while it lasts."""
    main_window = getattr(QApplication.instance(), 'main_window', None)
    if main_window is not None:
        main_window.set_on_air(on_air)


class PodcastWatcher(QObject):
    REDIAL_GRACE = 30       # s

    current = None          # the one podcast watched

    def __init__(self, session, account, do_not_disturb=False):
        super(PodcastWatcher, self).__init__()
        self.session = None
        self.room = session.room
        self.account = account
        self.do_not_disturb = bool(do_not_disturb) and account is not None and account is not BonjourAccount()
        self.waiting = False        # the room ended by itself: a rejoin expected
        self.waited = 0
        self.timer = QTimer(self)
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self._tick)
        if self.do_not_disturb:
            ActivityLog().info(f'[conference] Do Not Disturb on for {account.id} while on air in {session.room}')
            _show_on_air(True)
        PodcastWatcher.current = self
        self.attach(session)

    def attach(self, session):
        self._detach()
        if self.waiting:
            ActivityLog().info(f'[conference] The podcast in {session.room} goes on (rejoined)')
        self.session = session
        self.room = session.room
        self.waiting = False
        self.timer.stop()
        session.stateChanged.connect(self._SH_StateChanged)

    def _detach(self):
        if self.session is not None:
            try:
                self.session.stateChanged.disconnect(self._SH_StateChanged)
            except TypeError:
                pass

    def _SH_StateChanged(self, state, reason):
        if state != 'terminated':
            return
        self._detach()
        if reason == 'left':
            self.finish('left')
            return
        ActivityLog().info(f'[conference] The podcast in {self.room} ended by itself ({reason}): waiting {self.REDIAL_GRACE}s for a rejoin')
        self.waiting = True
        self.waited = 0
        self.timer.start()

    def _tick(self):
        if not self.waiting:
            self.timer.stop()
            return
        self.waited += 1
        if not mixer_present():
            self.finish('AG Podcast Mixer is gone')
        elif self.waited >= self.REDIAL_GRACE:
            self.finish('not rejoined')

    def finish(self, why, keep_devices=False):
        self.timer.stop()
        self._detach()
        self.waiting = False
        if PodcastWatcher.current is self:
            PodcastWatcher.current = None
        ActivityLog().info(f'[conference] The podcast in {self.room} is over ({why})')
        if self.do_not_disturb:
            self.do_not_disturb = False
            ActivityLog().info(f'[conference] Do Not Disturb off for {self.account.id}: the podcast ended')
            _show_on_air(False)
        if not keep_devices and PodcastWatcher.current is None:     # (another podcast on: its devices kept)
            settings = SIPSimpleSettings()
            if settings.audio.input_device != 'system_default' or settings.audio.output_device != 'system_default':
                ActivityLog().info(f'[conference] Audio back to the system default devices (were {settings.audio.input_device}, {settings.audio.output_device})')
                settings.audio.input_device = 'system_default'
                settings.audio.output_device = 'system_default'
                settings.save()
        self.session = None
