def __init__(self):
     super(ClubsController, self).__init__()
     self.__subscriptions = {}
     self.__isAppsNotifyShown = False
     self._requestsCtrl = ClubRequestsController(self)
     self._accountProfile = _AccountClubProfile(self)
     self._seasonsCache = ClubsSeasonsCache(self)
     self._availabilityCtrl = ClubAvailabilityController()
 def __init__(self):
     super(ClubsController, self).__init__()
     self.__subscriptions = {}
     self.__isAppsNotifyShown = False
     self._requestsCtrl = ClubRequestsController(self)
     self._accountProfile = _AccountClubProfile(self)
     self._seasonsCache = ClubsSeasonsCache(self)
     self._availabilityCtrl = ClubAvailabilityController()
class ClubsController(subscriptions.ClubsListeners):

    def __init__(self):
        super(ClubsController, self).__init__()
        self.__subscriptions = {}
        self.__isAppsNotifyShown = False
        self._requestsCtrl = ClubRequestsController(self)
        self._accountProfile = _AccountClubProfile(self)
        self._seasonsCache = ClubsSeasonsCache(self)
        self._availabilityCtrl = ClubAvailabilityController()

    def init(self):
        g_messengerEvents.users.onUsersListReceived += self.__onUsersListReceived
        self._seasonsCache.init()

    def fini(self):
        self._seasonsCache.fini()
        g_messengerEvents.users.onUsersListReceived -= self.__onUsersListReceived
        self.stop()
        self._requestsCtrl.fini()
        self.__subscriptions.clear()
        self._availabilityCtrl.stop()

    def start(self):
        clubsMgr = getClientClubsMgr()
        if clubsMgr is not None:
            clubsMgr.onClientClubsChanged += self.__onClientClubsChanged
            clubsMgr.onClientClubsNotification += self.__onClientClubsNotification
            clubsMgr.onClientClubsUnitInfoChanged += self.__onClientClubsUnitInfoChanged
        g_playerEvents.onCenterIsLongDisconnected += self.__onCenterIsLongDisconnected
        g_clientUpdateManager.addCallbacks({'cache.relatedToClubs': self.__onSpaAttrChanged,
         'cache.eSportSeasonState': self.__onSeasonStateChanged})
        self._accountProfile.resync(firstInit=True)
        self._seasonsCache.start()
        self._availabilityCtrl.start()
        return

    def stop(self, isDisconnected = False):
        self._seasonsCache.stop()
        if isDisconnected:
            self.__isAppsNotifyShown = False
            clearInvitesIDs()
        g_clientUpdateManager.removeObjectCallbacks(self)
        g_playerEvents.onCenterIsLongDisconnected -= self.__onCenterIsLongDisconnected
        clubsMgr = getClientClubsMgr()
        if clubsMgr is not None:
            clubsMgr.onClientClubsNotification -= self.__onClientClubsNotification
            clubsMgr.onClientClubsChanged -= self.__onClientClubsChanged
            clubsMgr.onClientClubsUnitInfoChanged -= self.__onClientClubsUnitInfoChanged
        self._accountProfile.stop()
        self._requestsCtrl.stopProcessing()
        for s in self.__subscriptions.itervalues():
            s.stop()

        self.__subscriptions.clear()
        self._availabilityCtrl.stop()
        return

    def markAppsNotificationShown(self):
        self.__isAppsNotifyShown = True

    def isAppsNotificationShown(self):
        return self.__isAppsNotifyShown

    def getAvailabilityCtrl(self):
        return self._availabilityCtrl

    def addListener(self, listener, forceResync = False):
        if not self._accountProfile.isSynced():
            self._accountProfile.resync(forceResync=forceResync)
        super(ClubsController, self).addListener(listener)

    def addClubListener(self, clubDbID, listener, subscriptionType, forceResync = False):
        if not self._accountProfile.isSynced():
            self._accountProfile.resync(forceResync=forceResync)
        s = self.__subscriptions.setdefault(clubDbID, subscriptions._Subscription(clubDbID, subscriptionType, self))
        s.addListener(listener)
        s.start()

    def removeClubListener(self, clubDbID, listener):
        if clubDbID in self.__subscriptions:
            s = self.__subscriptions[clubDbID]
            s.removeListener(listener)

    def getClub(self, clubDbID):
        if clubDbID in self.__subscriptions:
            return self.__subscriptions[clubDbID].getClub()
        else:
            return None

    @async
    def requestClubSeasons(self, clubDbID, callback):
        seasons = self._seasonsCache.getSeasons(clubDbID)
        if len(seasons):
            callback(seasons)
            return

        def _cbWrapper(result):
            if result.isSuccess():
                data = self._seasonsCache.putClubSeasons(clubDbID, result.data)
            else:
                data = {}
            callback(data)

        self._requestsCtrl.request(club_ctx.GetClubSeasonsCtx(clubDbID), callback=_cbWrapper, allowDelay=True)

    def getProfile(self):
        return self._accountProfile

    def isSubscribed(self, clubDbID):
        return clubDbID in self.__subscriptions and self.__subscriptions[clubDbID].isSubscribed()

    @classmethod
    def getSeasonState(cls):
        clubsMgr = getClientClubsMgr()
        if clubsMgr is not None:
            return SeasonState(clubsMgr.getESportSeasonState())
        else:
            return SeasonState(CLUBS_SEASON_STATE.INACTIVE)

    @classmethod
    def getSeasons(cls):
        clubsMgr = getClientClubsMgr()
        if clubsMgr is not None:
            return sorted(map(lambda (sID, d): SeasonInfo(sID, 0, 0, d), clubsMgr.getESportSeasons().iteritems()))
        else:
            return []

    @classmethod
    def getSeasonInfo(cls, seasonID):
        clubsMgr = getClientClubsMgr()
        if clubsMgr is not None:
            dossier = clubsMgr.getESportSeasons().get(seasonID)
            if dossier is not None:
                return SeasonInfo(seasonID, 0, 0, dossier)
        return

    @async
    @process
    def sendRequest(self, ctx, callback, allowDelay = None):
        yield lambda callback: callback(None)
        if ctx.getConfirmID():
            success = yield DialogsInterface.showI18nConfirmDialog(ctx.getConfirmID())
            if not success:
                return

        def _cbWrapper(result):
            isNeedToChangeState = False
            if not result.isSuccess():
                isNeedToChangeState = result.code in WEB_CMD_RESULT.WEB_UNAVAILABLE_ERRORS
                _showError(result, ctx)
            callback(result)
            if isNeedToChangeState:
                self._accountProfile._changeState(states.UnavailableClubsState())

        self._requestsCtrl.request(ctx, callback=_cbWrapper, allowDelay=allowDelay)

    def getRequestCtrl(self):
        return self._requestsCtrl

    def getState(self):
        return self._accountProfile.getState()

    def getLimits(self):
        return self._accountProfile.getState().getLimits()

    def getSeasonUserName(self, seasonID):
        season = self._seasonsCache.getSeasonCommonInfo(seasonID)
        if season:
            return season.getSeasonUserName()
        return ''

    def getCompletedSeasons(self):
        return self._seasonsCache.getCompletedSeasons()

    def _removeSubscription(self, clubDbID):
        if clubDbID in self.__subscriptions:
            self.__subscriptions[clubDbID].stop()

    def __onClientClubsChanged(self):
        self._accountProfile.resync()

    def __onClientClubsNotification(self, notificationType, notice):
        if notificationType == ACCOUNT_NOTIFICATION_TYPE.CLUB_CREATED:
            self.notify('onClubCreated', notice.clubDBID)
        self._accountProfile.resync()

    def __onCenterIsLongDisconnected(self, _):
        self._accountProfile.resync()

    def __onUsersListReceived(self, tags):
        self._accountProfile._onUsersListReceived(tags)

    def __onSpaAttrChanged(self, isRelatedToClubs):
        self.notify('onAccountClubRelationChanged', isRelatedToClubs)
        self._accountProfile.resync()

    def __onSeasonStateChanged(self, state):
        seasonState = SeasonState(state)
        self.notify('onClubsSeasonStateChanged', seasonState)
        self._accountProfile.resync()
        if seasonState.isFinished():
            self._seasonsCache.updateCompletedSeasons(force=True)

    def __onClientClubsUnitInfoChanged(self, clubDbID, unit):
        if clubDbID in self.__subscriptions:
            unitInfo = _UnitInfo(*unit) if unit else None
            self.__subscriptions[clubDbID].notify('onClubUnitInfoChanged', unitInfo)
        return

    def __repr__(self):
        return 'ClubsCtrl(profile = %s, subscriptions = %s)' % (str(self._accountProfile), self.__subscriptions.keys())
class ClubsController(subscriptions.ClubsListeners):

    def __init__(self):
        super(ClubsController, self).__init__()
        self.__subscriptions = {}
        self.__isAppsNotifyShown = False
        self._requestsCtrl = ClubRequestsController(self)
        self._accountProfile = _AccountClubProfile(self)
        self._seasonsCache = ClubsSeasonsCache(self)
        self._availabilityCtrl = ClubAvailabilityController()

    def init(self):
        g_messengerEvents.users.onUsersListReceived += self.__onUsersListReceived
        self._seasonsCache.init()

    def fini(self):
        self._seasonsCache.fini()
        g_messengerEvents.users.onUsersListReceived -= self.__onUsersListReceived
        self.stop()
        self._requestsCtrl.fini()
        self.__subscriptions.clear()
        self._availabilityCtrl.stop()

    def start(self):
        clubsMgr = getClientClubsMgr()
        if clubsMgr is not None:
            clubsMgr.onClientClubsChanged += self.__onClientClubsChanged
            clubsMgr.onClientClubsNotification += self.__onClientClubsNotification
            clubsMgr.onClientClubsUnitInfoChanged += self.__onClientClubsUnitInfoChanged
        g_playerEvents.onCenterIsLongDisconnected += self.__onCenterIsLongDisconnected
        g_clientUpdateManager.addCallbacks({'cache.relatedToClubs': self.__onSpaAttrChanged,
         'cache.eSportSeasonState': self.__onSeasonStateChanged})
        self._accountProfile.resync(firstInit=True)
        self._seasonsCache.start()
        self._availabilityCtrl.start()

    def stop(self, isDisconnected = False):
        self._seasonsCache.stop()
        if isDisconnected:
            self.__isAppsNotifyShown = False
            clearInvitesIDs()
        g_clientUpdateManager.removeObjectCallbacks(self)
        g_playerEvents.onCenterIsLongDisconnected -= self.__onCenterIsLongDisconnected
        clubsMgr = getClientClubsMgr()
        if clubsMgr is not None:
            clubsMgr.onClientClubsNotification -= self.__onClientClubsNotification
            clubsMgr.onClientClubsChanged -= self.__onClientClubsChanged
            clubsMgr.onClientClubsUnitInfoChanged -= self.__onClientClubsUnitInfoChanged
        self._accountProfile.stop()
        self._requestsCtrl.stopProcessing()
        for s in self.__subscriptions.itervalues():
            s.stop()

        self.__subscriptions.clear()
        self._availabilityCtrl.stop()

    def markAppsNotificationShown(self):
        self.__isAppsNotifyShown = True

    def isAppsNotificationShown(self):
        return self.__isAppsNotifyShown

    def getAvailabilityCtrl(self):
        return self._availabilityCtrl

    def addListener(self, listener, forceResync = False):
        if not self._accountProfile.isSynced():
            self._accountProfile.resync(forceResync=forceResync)
        super(ClubsController, self).addListener(listener)

    def addClubListener(self, clubDbID, listener, subscriptionType, forceResync = False):
        if not self._accountProfile.isSynced():
            self._accountProfile.resync(forceResync=forceResync)
        s = self.__subscriptions.setdefault(clubDbID, subscriptions._Subscription(clubDbID, subscriptionType, self))
        s.addListener(listener)
        s.start()

    def removeClubListener(self, clubDbID, listener):
        if clubDbID in self.__subscriptions:
            s = self.__subscriptions[clubDbID]
            s.removeListener(listener)

    def getClub(self, clubDbID):
        if clubDbID in self.__subscriptions:
            return self.__subscriptions[clubDbID].getClub()

    @async
    def requestClubSeasons(self, clubDbID, callback):
        seasons = self._seasonsCache.getSeasons(clubDbID)
        if len(seasons):
            callback(seasons)
            return

        def _cbWrapper(result):
            if result.isSuccess():
                data = self._seasonsCache.putClubSeasons(clubDbID, result.data)
            else:
                data = {}
            callback(data)

        self._requestsCtrl.request(club_ctx.GetClubSeasonsCtx(clubDbID), callback=_cbWrapper, allowDelay=True)

    def getProfile(self):
        return self._accountProfile

    def isSubscribed(self, clubDbID):
        return clubDbID in self.__subscriptions and self.__subscriptions[clubDbID].isSubscribed()

    @classmethod
    def getSeasonState(cls):
        clubsMgr = getClientClubsMgr()
        if clubsMgr is not None:
            return SeasonState(clubsMgr.getESportSeasonState())
        return SeasonState(CLUBS_SEASON_STATE.INACTIVE)

    @classmethod
    def getSeasons(cls):
        clubsMgr = getClientClubsMgr()
        if clubsMgr is not None:
            return sorted(map(lambda (sID, d): SeasonInfo(sID, 0, 0, d), clubsMgr.getESportSeasons().iteritems()))
        return []

    @classmethod
    def getSeasonInfo(cls, seasonID):
        clubsMgr = getClientClubsMgr()
        if clubsMgr is not None:
            dossier = clubsMgr.getESportSeasons().get(seasonID)
            if dossier is not None:
                return SeasonInfo(seasonID, 0, 0, dossier)

    @async
    @process
    def sendRequest(self, ctx, callback, allowDelay = None):
        yield lambda callback: callback(None)
        if ctx.getConfirmID():
            success = yield DialogsInterface.showI18nConfirmDialog(ctx.getConfirmID())
            if not success:
                return

        def _cbWrapper(result):
            isNeedToChangeState = False
            if not result.isSuccess():
                isNeedToChangeState = result.code in WEB_CMD_RESULT.WEB_UNAVAILABLE_ERRORS
                _showError(result, ctx)
            callback(result)
            if isNeedToChangeState:
                self._accountProfile._changeState(states.UnavailableClubsState())

        self._requestsCtrl.request(ctx, callback=_cbWrapper, allowDelay=allowDelay)

    def getRequestCtrl(self):
        return self._requestsCtrl

    def getState(self):
        return self._accountProfile.getState()

    def getLimits(self):
        return self._accountProfile.getState().getLimits()

    def getSeasonUserName(self, seasonID):
        season = self._seasonsCache.getSeasonCommonInfo(seasonID)
        if season:
            return season.getSeasonUserName()
        return ''

    def getCompletedSeasons(self):
        return self._seasonsCache.getCompletedSeasons()

    def _removeSubscription(self, clubDbID):
        if clubDbID in self.__subscriptions:
            self.__subscriptions[clubDbID].stop()

    def __onClientClubsChanged(self):
        self._accountProfile.resync()

    def __onClientClubsNotification(self, notificationType, notice):
        if notificationType == ACCOUNT_NOTIFICATION_TYPE.CLUB_CREATED:
            self.notify('onClubCreated', notice.clubDBID)
        self._accountProfile.resync()

    def __onCenterIsLongDisconnected(self, _):
        self._accountProfile.resync()

    def __onUsersListReceived(self, tags):
        self._accountProfile._onUsersListReceived(tags)

    def __onSpaAttrChanged(self, isRelatedToClubs):
        self.notify('onAccountClubRelationChanged', isRelatedToClubs)
        self._accountProfile.resync()

    def __onSeasonStateChanged(self, state):
        seasonState = SeasonState(state)
        self.notify('onClubsSeasonStateChanged', seasonState)
        self._accountProfile.resync()
        if seasonState.isFinished():
            self._seasonsCache.updateCompletedSeasons(force=True)

    def __onClientClubsUnitInfoChanged(self, clubDbID, unit):
        if clubDbID in self.__subscriptions:
            unitInfo = _UnitInfo(*unit) if unit else None
            self.__subscriptions[clubDbID].notify('onClubUnitInfoChanged', unitInfo)

    def __repr__(self):
        return 'ClubsCtrl(profile = %s, subscriptions = %s)' % (str(self._accountProfile), self.__subscriptions.keys())