# -*- mode: python; indent-tabs-mode: nil; py-indent-offset: 4; coding: utf-8 -*-
from contacts import basecontact
import random
import threading
import common.tox_save as tox_save
from middleware.threads import invoke_in_main_thread

iUMAXINT = 4294967295
iRECONNECT = 50

global LOG
import logging
LOG = logging.getLogger('app.'+__name__)

class Profile(basecontact.BaseContact, tox_save.ToxSave):
    """
    Profile of current toxygen user.
    """
    def __init__(self, profile_manager, tox, screen, contacts_provider, reset_action, app=None):
        """
        :param tox: tox instance
        :param screen: ref to main screen
        """
        assert tox
        basecontact.BaseContact.__init__(self,
                                         profile_manager,
                                         tox.self_get_name(),
                                         tox.self_get_status_message(),
                                         screen,
                                         tox.self_get_address())
        tox_save.ToxSave.__init__(self, tox)
        self._screen = screen
        self._messages = screen.messages
        self._contacts_provider = contacts_provider
        self._reset_action = reset_action
        self._waiting_for_reconnection = False
        self._timer = None
        self._app = app

    # Edit current user's data

    def change_status(self) -> None:
        """
        Changes status of user (online, away, busy)
        """
        if self._status is not None:
            self.set_status((self._status + 1) % 3)

    def set_status(self, status) -> None:
        super().set_status(status)
        if status is not None:
            self._tox.self_set_status(status)
        elif not self._waiting_for_reconnection:
            self._waiting_for_reconnection = True
            self._timer = threading.Timer(iRECONNECT, self._reconnect)
            self._timer.start()

    def set_name(self, value) -> None:
        if self.name == value:
            return
        super().set_name(value)
        self._tox.self_set_name(self._name)

    def set_status_message(self, value) -> None:
        super().set_status_message(value)
        self._tox.self_set_status_message(self._status_message)

    def set_new_nospam(self):
        """Sets new nospam part of tox id"""
        self._tox.self_set_nospam(random.randint(0, iUMAXINT))  # no spam - uint32
        self._tox_id = self._tox.self_get_address()
        self._sToxId = self._tox.self_get_address()
        return self._sToxId

    # Reset

    def restart(self) -> None:
        """
        Recreate tox instance
        """
        self.status = None
        invoke_in_main_thread(self._reset_action)

    def _reconnect(self) -> None:
        self._waiting_for_reconnection = False
        if self._app and self._app.bAppExiting:
            # dont do anything after the app has been shipped
            # there's a segv that results
            return
        contacts = self._contacts_provider.get_all_friends()
        all_friends_offline = all(list(map(lambda x: x.status is None, contacts)))
        if self.status is None or (all_friends_offline and len(contacts)):
            self._waiting_for_reconnection = True
            self.restart()
            self._timer = threading.Timer(iRECONNECT, self._reconnect)
            self._timer.start()

# Current thread 0x00007901a13ccb80 (most recent call first):
#   File "/usr/local/lib/python3.11/site-packages/toxygen_wrapper/tox.py", line 826 in self_get_friend_list_size
#   File "/usr/local/lib/python3.11/site-packages/toxygen_wrapper/tox.py", line 838 in self_get_friend_list
#   File "/mnt/o/var/local/src/toxygen/toxygen/contacts/contact_provider.py", line 45 in get_all_friends
#   File "/mnt/o/var/local/src/toxygen/toxygen/contacts/profile.py", line 90 in _reconnect
#   File "/usr/lib/python3.11/threading.py", line 1401 in run
#   File "/usr/lib/python3.11/threading.py", line 1045 in _bootstrap_inner
#   File "/usr/lib/python3.11/threading.py", line 1002 in _bootstrap
#

