示例#1
0
def main(file_name, file_format, lottery_template, output_file):
    participants = Participants()
    participants.read_data_from_file(file_name, file_format)
    prizes = Prizes(specify_lottery_template(lottery_template))
    prizes.load_prize_data()
    lottery = Lottery(prizes, participants)
    lottery.award_prizes()
    lottery.save_awarded_prizes_data_to_json_file(output_file)
示例#2
0
 def __init__(self):
   self.__channel_users = {}
   self.__user_ids = {}
   self.__bracket = TourneyTree()
   self.__last_post = None
   self.participants = Participants()
   self.presets = Presets()
   self.is_joinable = False
 def __init__(self, dict_info={}):
     if dict_info != {}:
         if "gameCreation" in dict_info.keys():
             self.gameCreation = dict_info["gameCreation"]
         if "gameDuration" in dict_info.keys():
             self.gameDuration = dict_info["gameDuration"]
         if "gameId" in dict_info.keys():
             self.gameId = dict_info["gameId"]
         if "gameMode" in dict_info.keys():
             self.gameMode = dict_info["gameMode"]
         if "gameType" in dict_info.keys():
             self.gameType = dict_info["gameType"]
         if "gameVersion" in dict_info.keys():
             self.gameVersion = dict_info["gameVersion"]
         if "mapId" in dict_info.keys():
             self.mapId = dict_info["mapId"]
         if "platformId" in dict_info.keys():
             self.platformId = dict_info["platformId"]
         if "queueId" in dict_info.keys():
             self.queueId = dict_info["queueId"]
         if "seasonId" in dict_info.keys():
             self.seasonId = dict_info["seasonId"]
         if "participantIdentities" in dict_info.keys():
             self.participantIdentities = [ParticipantIdentities(p) for p in dict_info["participantIdentities"]]
         if "participants" in dict_info.keys():
             self.participants = [Participants(p) for p in dict_info["participants"]]
         if "teams" in dict_info.keys():
             self.teams = [Teams(p) for p in dict_info["teams"]]
示例#4
0
 def __init__(self, id, contributor):
     """ """
     NyFolder.__dict__['__init__'](self, id, contributor)
     self.participants = Participants('participants')
     self.email_sender = EmailSender('email_sender')
     self.survey_required = False
     self.allow_register = True
     self.restrict_items = True
class CompleteGame:
    gameCreation = 0
    gameDuration = 0
    gameId = 0
    gameMode = ""
    gameType = ""
    gameVersion = ""
    mapId = 0
    platformId = ""
    queueId = 0
    seasonId = 0
    participantIdentities = [ParticipantIdentities()]
    teams = [Teams()]
    participants = [Participants()]

    def __init__(self, dict_info={}):
        if dict_info != {}:
            if "gameCreation" in dict_info.keys():
                self.gameCreation = dict_info["gameCreation"]
            if "gameDuration" in dict_info.keys():
                self.gameDuration = dict_info["gameDuration"]
            if "gameId" in dict_info.keys():
                self.gameId = dict_info["gameId"]
            if "gameMode" in dict_info.keys():
                self.gameMode = dict_info["gameMode"]
            if "gameType" in dict_info.keys():
                self.gameType = dict_info["gameType"]
            if "gameVersion" in dict_info.keys():
                self.gameVersion = dict_info["gameVersion"]
            if "mapId" in dict_info.keys():
                self.mapId = dict_info["mapId"]
            if "platformId" in dict_info.keys():
                self.platformId = dict_info["platformId"]
            if "queueId" in dict_info.keys():
                self.queueId = dict_info["queueId"]
            if "seasonId" in dict_info.keys():
                self.seasonId = dict_info["seasonId"]
            if "participantIdentities" in dict_info.keys():
                self.participantIdentities = [ParticipantIdentities(p) for p in dict_info["participantIdentities"]]
            if "participants" in dict_info.keys():
                self.participants = [Participants(p) for p in dict_info["participants"]]
            if "teams" in dict_info.keys():
                self.teams = [Teams(p) for p in dict_info["teams"]]

    def __str__(self):
        return "GameId: " + str(self.gameId) + "\n" + \
               "GameDuration: " + duration_game_str(self.gameDuration) + "\n" + \
               "GameMode: " + str(self.gameMode) + "\n" + \
               "GameType: " + str(self.gameType) + "\n" + \
               "QueueId: " + queue_str(self.queueId) + "\n" + \
               "SeasonId: " + season_str(self.seasonId)
示例#6
0
class NyMeeting(NyContentData, NyFolder):
    """ """

    implements(INyMeeting)

    meta_type = config['meta_type']
    meta_label = config['label']
    icon = 'misc_/NaayaContent/NyMeeting.gif'
    icon_marked = 'misc_/NaayaContent/NyMeeting_marked.gif'

    attendees_icon = 'misc_/NaayaContent/Attendees.jpg'
    email_icon = 'misc_/NaayaContent/Email.jpg'
    icalendar_icon = 'misc_/NaayaContent/iCalendar.jpg'

    agenda_icon = 'misc_/NaayaContent/Agenda.png'
    minutes_icon = 'misc_/NaayaContent/Minutes.png'
    survey_icon = 'misc_/NaayaContent/survey.gif'

    default_form_id = 'meeting_index'

    manage_options = NyFolder.manage_options

    security = ClassSecurityInfo()

    __allow_groups__ = SignupUsersTool()
    __ac_roles__ = (PARTICIPANT_ROLE, WAITING_ROLE)

    def __init__(self, id, contributor):
        """ """
        NyFolder.__dict__['__init__'](self, id, contributor)
        self.participants = Participants('participants')
        self.email_sender = EmailSender('email_sender')
        self.survey_required = False
        self.allow_register = True
        self.restrict_items = True

    security.declareProtected(view, 'getParticipants')

    def getParticipants(self):
        return self.participants

    security.declareProtected(PERMISSION_ADMIN_MEETING, 'getEmailSender')

    def getEmailSender(self):
        return self.email_sender

    security.declarePrivate('objectkeywords')

    def objectkeywords(self, lang):
        return u' '.join([self._objectkeywords(lang), self.geo_address()])

    security.declarePrivate('export_this_tag_custom')

    def export_this_tag_custom(self):
        return ('location="%s" start_date="%s" end_date="%s" max_participants='
                '"%s" agenda_pointer="%s" minutes_pointer="%s" survey_pointer='
                '"%s" contact_person="%s" contact_email="%s"' %
                (self.utXmlEncode(self.geo_address()),
                 self.utXmlEncode(self.utNoneToEmpty(
                     self.interval.start_date)),
                 self.utXmlEncode(self.utNoneToEmpty(self.interval.end_date)),
                 self.utXmlEncode(self.max_participants),
                 self.utXmlEncode(self.agenda_pointer),
                 self.utXmlEncode(self.minutes_pointer),
                 self.utXmlEncode(self.survey_pointer),
                 self.utXmlEncode(self.contact_person),
                 self.utXmlEncode(self.contact_email)))

    security.declarePrivate('export_this_body_custom')

    def export_this_body_custom(self):
        r = []
        return ''.join(r)

    security.declarePrivate('syndicateThis')

    def syndicateThis(self, lang=None):
        l_site = self.getSite()
        if lang is None:
            lang = self.gl_get_selected_language()
        item = rss_item_for_object(self, lang)
        syndication_tool = self.getSyndicationTool()
        namespaces = syndication_tool.getNamespaceItemsList()
        nsmap = get_nsmap(namespaces)
        dc_namespace = nsmap['dc']
        ev_namespace = nsmap['ev']
        Dc = ElementMaker(namespace=dc_namespace, nsmap=nsmap)
        Ev = ElementMaker(namespace=ev_namespace, nsmap=nsmap)
        the_rest = Dc.root(
            Dc.type('Meeting'),
            Dc.format('text'),
            Dc.source(l_site.getLocalProperty('publisher', lang)),
            Dc.creator(l_site.getLocalProperty('creator', lang)),
            Dc.publisher(l_site.getLocalProperty('publisher', lang)),
            Ev.startdate(self.utShowFullDateTimeHTML(
                self.interval.start_date)),
            Ev.enddate(self.utShowFullDateTimeHTML(self.interval.end_date)),
            Ev.location(self.geo_address()),
            Ev.organizer(self.contact_person),
            Ev.type('Meeting')
            )
        item.extend(the_rest)
        return etree.tostring(item, xml_declaration=False, encoding="utf-8")

    def _check_meeting_dates(self, form_errors):
        _startdate = getattr(self, 'interval.start_date', '')
        _enddate = getattr(self, 'interval.end_date', '')
        if _startdate and _enddate:
            if _startdate > _enddate:
                form_errors.setdefault('interval.start_date', [])
                form_errors['interval.start_date'].append(
                    'The start date should be before the end date')
                form_errors.setdefault('interval.end_date', [])
                form_errors['interval.end_date'].append(
                    'The start date should be before the end date')

    def _check_meeting_pointers(self, form_errors):
        if getattr(self, 'agenda_pointer', ''):
            try:
                self.unrestrictedTraverse(str(self.agenda_pointer))
            except KeyError:
                form_errors.setdefault('agenda_pointer', [])
                form_errors['agenda_pointer'].append(
                    'No object at the selected path')
        if getattr(self, 'survey_pointer', ''):
            try:
                self.unrestrictedTraverse(str(self.survey_pointer))
            except KeyError:
                form_errors.setdefault('survey_pointer', [])
                form_errors['survey_pointer'].append(
                    'No object at the selected path')
        if getattr(self, 'minutes_pointer', ''):
            try:
                self.unrestrictedTraverse(str(self.minutes_pointer))
            except KeyError:
                form_errors.setdefault('minutes_pointer', [])
                form_errors['minutes_pointer'].append(
                    'No object at the selected path')

    security.declarePrivate('meeting_submitted_form')

    def meeting_submitted_form(self, REQUEST_form, _lang=None,
                               _all_values=True, _override_releasedate=None):
        """
        this should be used for the meeting instead of process_submitted_form
        """
        form_errors = super(NyMeeting, self).process_submitted_form(
            REQUEST_form, _lang, _all_values, _override_releasedate)
        self._check_meeting_dates(form_errors)  # can modify form_errors
        self._check_meeting_pointers(form_errors)  # can modify form_errors

        self._set_items_view_permissions()

        return form_errors

    def _set_items_view_permissions(self):
        if getattr(self, 'restrict_items', True):
            agenda_pointer = str(getattr(self, 'agenda_pointer', ''))
            site = self.getSite()
            for item in self.objectValues():
                if relative_object_path(item, site) == agenda_pointer:
                    _unrestrict_meeting_item_view(item)
                else:
                    _restrict_meeting_item_view(item)
        else:
            for item in self.objectValues():
                _unrestrict_meeting_item_view(item)

    # zmi actions
    security.declareProtected(view_management_screens, 'manageProperties')

    def manageProperties(self, REQUEST=None, **kwargs):
        """ """
        if not self.checkPermissionEditObject():
            raise EXCEPTION_NOTAUTHORIZED(EXCEPTION_NOTAUTHORIZED_MSG)

        if REQUEST is not None:
            schema_raw_data = dict(REQUEST.form)
        else:
            schema_raw_data = kwargs
        _lang = schema_raw_data.pop('_lang', schema_raw_data.pop('lang', None))
        _releasedate = self.process_releasedate(
            schema_raw_data.pop('releasedate', ''), self.releasedate)
        _approved = int(bool(schema_raw_data.pop('approved', False)))

        form_errors = self.meeting_submitted_form(
            schema_raw_data, _lang, _override_releasedate=_releasedate)
        if form_errors:
            raise ValueError(form_errors.popitem()[1])  # pick a random error

        self.custom_index = schema_raw_data.pop('custom_index', '')

        if _approved != self.approved:
            if _approved == 0:
                _approved_by = None
            else:
                _approved_by = self.REQUEST.AUTHENTICATED_USER.getUserName()
            self.approveThis(_approved, _approved_by)

        self._p_changed = 1
        self.recatalogNyObject(self)
        if REQUEST:
            REQUEST.RESPONSE.redirect('manage_edit_html?save=ok')

    # site actions
    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'saveProperties')

    def saveProperties(self, REQUEST=None, **kwargs):
        """ """
        if not self.checkPermissionEditObject():
            raise EXCEPTION_NOTAUTHORIZED(EXCEPTION_NOTAUTHORIZED_MSG)

        obj = self

        if REQUEST is not None:
            schema_raw_data = dict(REQUEST.form)
        else:
            schema_raw_data = kwargs
        _lang = schema_raw_data.pop('_lang', schema_raw_data.pop('lang', None))
        _releasedate = self.process_releasedate(
            schema_raw_data.pop('releasedate', ''), obj.releasedate)

        form_errors = self.meeting_submitted_form(
            schema_raw_data, _lang, _override_releasedate=_releasedate)
        if schema_raw_data.get('survey_required') and not schema_raw_data.get(
                'survey_pointer'):
            form_errors['survey_required'] = [
                'Cannot set survey required without a link to a survey']

        if not form_errors:
            self._p_changed = 1
            self.recatalogNyObject(self)
            # log date
            if self.eionet_meeting(survey=True):
                portal_map = self.getGeoMapTool()
                meeting_type = portal_map.getSymbolTitle(self.geo_type)
                survey_ids = [survey.getId() for survey in
                              self.objectValues('Naaya Mega Survey')]
                if EIONET_SURVEYS[meeting_type]['id'] not in survey_ids:
                    _create_eionet_survey(self)
                eionet_survey = _get_eionet_survey(self)
                start_date = DateTime(self.interval.start_date.year,
                                      self.interval.start_date.month,
                                      self.interval.start_date.day)
                if start_date != eionet_survey.releasedate:
                    eionet_survey.releasedate = start_date
                    eionet_survey.expirationdate = start_date + 13
                if start_date + 13 != eionet_survey.expirationdate:
                    eionet_survey.expirationdate = start_date + 13
            contributor = self.REQUEST.AUTHENTICATED_USER.getUserName()
            auth_tool = self.getAuthenticationTool()
            auth_tool.changeLastPost(contributor)
            notify(NyContentObjectEditEvent(self, contributor))
            if REQUEST:
                self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES,
                                         date=self.utGetTodayDate())
                REQUEST.RESPONSE.redirect('%s/edit_html?lang=%s' %
                                          (self.absolute_url(), _lang))
        else:
            if REQUEST is not None:
                self._prepare_error_response(REQUEST, form_errors,
                                             schema_raw_data)
                REQUEST.RESPONSE.redirect('%s/edit_html?lang=%s' %
                                          (self.absolute_url(), _lang))
            else:
                raise ValueError(form_errors.popitem()[1])  # pick an error

    def checkPermissionParticipateInMeeting(self):
        """ """
        return (self.checkPermission(PERMISSION_PARTICIPATE_IN_MEETING) or
                self.checkPermissionAdminMeeting() or
                self.nfp_for_country())

    def checkPermissionAdminMeeting(self):
        """ """
        return self.checkPermission(PERMISSION_ADMIN_MEETING)

    def checkPermissionChangePermissions(self):
        """ """
        return self.nfp_for_country() or self.checkPermission(
            change_permissions)

    def isParticipant(self, userid=None):
        """ """
        participants = self.getParticipants()
        return participants.isParticipant(userid)

    def registration_status(self, username=None):
        """ """
        username = username or self.REQUEST.AUTHENTICATED_USER.getUserName()
        participants = self.getParticipants()
        a_subscriptions = participants.subscriptions._account_subscriptions
        subscriptions = a_subscriptions.itervalues()
        for subscriber in subscriptions:
            if username == subscriber.uid:
                return subscriber.accepted
        attendees = participants._get_attendees()
        attendee_data = attendees.get(username)
        if attendee_data:
            attendee_role = attendee_data['role']
            if attendee_role == 'Meeting Participant':
                return 'accepted'
            elif attendee_role == 'Meeting Waiting List':
                return 'new'
        return None

    security.declareProtected(view, 'get_survey')

    def get_survey(self):
        site = self.getSite()
        path = str(self.survey_pointer)
        if path:
            return site.unrestrictedTraverse(path, None)

    security.declareProtected(view, 'get_survey_questions')

    def get_survey_questions(self):
        survey = self.get_survey()
        if survey is not None and survey.meta_type == 'Naaya Mega Survey':
            questions = []
            for question in survey.getSortedWidgets():
                questions.append((question.id, question.title))
            return questions

    security.declareProtected(view, 'get_survey_answer')

    def get_survey_answer(self, uid, qid):
        survey = self.get_survey()
        if survey is not None and survey.meta_type == 'Naaya Mega Survey':
            question = getattr(survey, qid, None)
            if question:
                for answer in survey.objectValues('Naaya Survey Answer'):
                    if answer.respondent in [uid, 'signup:'+uid]:
                        try:
                            return question.get_value(getattr(answer.aq_base,
                                                              qid))
                        except AttributeError:
                            return ''
    # zmi pages
    security.declareProtected(view_management_screens, 'manage_edit_html')
    manage_edit_html = PageTemplateFile('zpt/meeting_manage_edit', globals())

    # site pages
    security.declareProtected(view, 'index_html')

    def index_html(self, REQUEST):
        """ """
        if self.survey_required and (self.registration_status() or
                                     self.isParticipant() or
                                     self.is_pending_signup()):
            survey_ob = self.get_survey()
            if (survey_ob is not None and
                    survey_ob.meta_type == 'Naaya Mega Survey'):
                answers = survey_ob.getAnswers()
                respondents = [a.respondent for a in answers]
                current_user = REQUEST.AUTHENTICATED_USER.getUserName()
                if current_user not in respondents:
                    REQUEST.RESPONSE.redirect(
                        '%s/%s' %
                        (self.getSite().absolute_url(), self.survey_pointer))

        tmpl = self.get_custom_index_template()
        if tmpl is None:
            # no custom_index was configured, or the template is missing
            tmpl = self.getFormsTool()['meeting_index'].aq_base.__of__(self)
        return tmpl(REQUEST)

    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'edit_html')

    def edit_html(self, REQUEST=None, RESPONSE=None):
        """ """
        return self.getFormsTool().getContent({'here': self}, 'meeting_edit')

    security.declareProtected(view, 'menusubmissions')

    def menusubmissions(self, REQUEST=None, RESPONSE=None):
        """ """
        return self.getFormsTool().getContent(
            {'here': self}, 'naaya.content.meeting.meeting_menusubmissions')

    security.declareProtected(view, 'get_ics')

    def get_ics(self, REQUEST):
        """ Export this meeting as 'ics' """

        cal = vobject.iCalendar()
        cal.add('prodid').value = '-//European Environment Agency//Naaya//EN'
        cal.add('method').value = 'PUBLISH'
        cal.add('vevent')

        cal.vevent.add('uid').value = self.absolute_url() + '/get_ics'
        cal.vevent.add('url').value = self.absolute_url()
        cal.vevent.add('summary').value = self.title_or_id()
        cal.vevent.add('description').value = html2text(self.description)
        header = ('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">\n'
                  '<HTML>\n'
                  '<HEAD>\n<TITLE>' + self.title_or_id() +
                  '</TITLE>\n</HEAD>\n<BODY>\n')
        footer = '\n</BODY>\n</HTML>'
        cal.vevent.add('X-ALT-DESC;FMTTYPE=text/html').value = \
            header + self.description + footer
        cal.vevent.add('transp').value = 'OPAQUE'

        modif_time = DT2dt(self.bobobase_modification_time())
        cal.vevent.add('dtstamp').value = modif_time

        interval = getattr(self, 'interval', None)
        if interval is None:
            # old object, backwards compatibility code
            # should run updates.ConvertMeetingDates
            log.warning("%s needs patch to use Interval", self.absolute_url(1))
            cal.vevent.add('dtstart').value = DT2dt(self.start_date).date()
            cal.vevent.add('dtend').value = (DT2dt(self.end_date).date() +
                                             datetime.timedelta(days=1))
        else:
            if interval.all_day:
                cal.vevent.add('dtstart').value = interval.start_date.date()
                cal.vevent.add('dtend').value = (interval.end_date.date() +
                                                 datetime.timedelta(days=1))
            else:
                cal.vevent.add('dtstart').value = interval.start_date
                cal.vevent.add('dtend').value = interval.end_date

        loc = []
        if getattr(self, 'location', False):
            loc.append(self.location)
        if self.geo_address():
            loc.append(self.geo_address())

        if loc:
            cal.vevent.add('location').value = ', '.join(loc)

        ics_data = cal.serialize()

        REQUEST.RESPONSE.setHeader('Content-Type', 'text/calendar')
        REQUEST.RESPONSE.setHeader('Content-Disposition',
                                   'attachment;filename=%s.ics' % self.getId())
        REQUEST.RESPONSE.write(ics_data)

    security.declareProtected(view, 'nfp_for_country')

    def nfp_for_country(self):
        """ """
        # if we are not in the Eionet network, NFPs don't get special treatment
        if not self.in_eionet():
            return ''
        auth_tool = self.getAuthenticationTool()
        user_id = self.REQUEST.AUTHENTICATED_USER.getId()
        if user_id:
            ldap_groups = auth_tool.get_ldap_user_groups(user_id)
            for group in ldap_groups:
                if 'eionet-nfp-cc-' in group[0]:
                    return group[0].replace('eionet-nfp-cc-', '')
                if 'eionet-nfp-mc-' in group[0]:
                    return group[0].replace('eionet-nfp-mc-', '')

    security.declareProtected(view, 'get_country')

    def get_country(self, country_code):
        """ """
        if country_code is None:
            return '-'
        return country_from_country_code.get(country_code, country_code)

    def get_countries(self):
        """ """
        countries = sorted(country_from_country_code.items(),
                           key=lambda x: x[1])
        return countries

    security.declareProtected(view, 'is_signup')

    def is_signup(self):
        """ """
        username = self.REQUEST.AUTHENTICATED_USER.getUserName()
        key = username.replace('signup:', '')
        return self.participants.getSubscriptions()._is_signup(key)

    security.declareProtected(view, 'is_pending_signup')

    def is_pending_signup(self):
        """ """
        username = self.REQUEST.AUTHENTICATED_USER.getUserName()
        key = username.replace('signup:', '')
        return self.participants.getSubscriptions()._is_pending_signup(key)

    # Compatibility code

    security.declarePublic('start_date')

    @property
    def start_date(self):
        d = self.interval.start_date
        return DateTime(d.year, d.month, d.day)

    security.declarePublic('start_date')

    @property
    def end_date(self):
        d = self.interval.end_date
        return DateTime(d.year, d.month, d.day)

    security.declarePublic('restrictedTraverse')

    def restrictedTraverse(self, path, default=_marker):
        handle_traverse_meeting(self, self.REQUEST)
        return self.unrestrictedTraverse(path, default, restricted=True)

    security.declarePublic('get_signup_details')

    def get_signup_details(self):
        """ Return a json with the signup details"""
        user_id = self.REQUEST.AUTHENTICATED_USER.getUserName()
        if user_id.startswith('signup:'):
            key = user_id.replace('signup:', '')
            signup = self.getParticipants().getSubscriptions().getSignup(key)
            if signup:
                signup_details = {
                    'name': signup.name,
                    'email': signup.email,
                    'organization': signup.organization,
                    'phone': signup.phone
                    }
                return json.dumps(signup_details)

    security.declarePublic('in_eionet')

    def in_eionet(self):
        """ Return if the meeting is part of the Eionet network"""
        return NETWORK_NAME.lower() == 'eionet'

    security.declarePublic('eionet_meeting')

    def eionet_meeting(self, survey=False):
        """ Check if the meeting is part of the so calles 'Eionet meetings'
        and if it should have an automatic survey"""
        if not self.in_eionet():
            return False
        portal_map = self.getGeoMapTool()
        meeting_type = portal_map.getSymbolTitle(self.geo_type)
        # if survey parameter is true, we want to know if this meeting
        # type requires an automatic survey
        if survey:
            if meeting_type in EIONET_SURVEYS:
                return True
        else:
            if meeting_type in EIONET_MEETINGS:
                return True
        return False
示例#7
0
import random
from participants import Participants 
from game import Game

turn = 0

print ('Введите имя игрока:')
name = input()
print ('Введите здоровье участников игры:')
inputHealth = input()

maxHealth = int(inputHealth)
user = Participants(name, maxHealth)
computer = Participants('Компьютер', maxHealth)

while True:
    turn += 1
    Game.battle(user, computer, turn, maxHealth)

    if user.getHealth() < 0:
        print('Ваше здоровье меньше 1, вы проиграли')
        break
    if computer.getHealth() < 0:
        print('Здоровье противника меньше 1, вы выиграли')
        break

input()
示例#8
0
class Tourney:
  '''
  This class provides methods to manage the tournament tree bracket.
  '''

  def __init__(self):
    self.__channel_users = {}
    self.__user_ids = {}
    self.__bracket = TourneyTree()
    self.__last_post = None
    self.participants = Participants()
    self.presets = Presets()
    self.is_joinable = False

  def set_last_post(self, last_post):
    self.__last_post = last_post
 
  def get_last_post(self):
    return self.__last_post
  
  def add_channel_user(self, player):
    self.__channel_users[player.get_user()] = player
    self.__user_ids[player.get_handle()] = player.get_user()

  # def remove_channel_user(self, player_id):
  #   player = self.__channel_users[player_id]
  #   user_id = player.get_user()
  #   handle =player.get_handle()

  #   del self.__channel_users[user_id]
  #   del self.__user_ids[handle]
       
  def singles(self):
    self.__last_post = None

    number_of_slots = 0
    number_of_presets = len(self.presets.get_all())
    is_random = number_of_presets == 0
    if is_random:
      if self.is_joinable:
        number_of_slots = len(self.participants.get_handles())
      else:
        number_of_slots = len(self.__channel_users)
    else:
      number_of_slots = number_of_presets

    if number_of_slots < 2:
      return "There are not enough players."

    response = ""
    team = None
    slots = []
    if is_random:
      users = {}
      if self.is_joinable:
        for participant in self.participants.get_handles():
          user_id = self.__user_ids[participant]
          users[user_id] = participant
      else:
        users = self.__channel_users

      for key in users:
        del(team)
        team = PlayerTeam()
        team.add_player(self.__channel_users[key])
        slots.append(team)
      response = "Singles bracket randomly generated."
    else:
      for handle in self.presets.get_all():
        if handle == "-bye-":
          del(team)
          team = PlayerTeam()
          slots.append(team)
        else:
          del(team)
          team = PlayerTeam()

          user_id = self.__user_ids[handle]
          player = self.__channel_users[user_id]
          team.add_player(player)

          slots.append(team)

      slots = self.__get_order_preset(slots)
      response = "Singles bracket generated from presets."

    self.__bracket.generate(slots, is_random)

    return response

  def doubles(self, user):
    self.__last_post = None
    
    number_of_slots = 0
    number_of_presets = len(self.presets.get_all())
    is_random = number_of_presets == 0
    if is_random:
      number_of_players = len(self.__channel_users)
      number_of_slots = number_of_players / 2
    else:
      number_of_players = number_of_presets
      number_of_slots = number_of_players / 2
      
    is_odd = number_of_players % 2 == 1    
    
    if number_of_slots < 2:
      return "There are not enough players."

    if is_odd and is_preset:
      return "There is an odd number of presets."

    response = ""
    team = None
    slots = []
    i = 0
    if is_random:
      players = []
      if self.is_joinable:
        users = {}
        for participant in self.participants.get_handles():
          user_id = self.__user_ids[participant]
          users[user_id] = participant
        for key in users:
          if not is_odd or key != user:
            players.append(self.__channel_users[key]) 
      else:
        for key in self.__channel_users:
          if not is_odd or key != user:
            players.append(self.__channel_users[key]) 

      for x in range(len(players)):
        rand_int = random.choice(range(len(players)))
        random_player = players[rand_int]
        del players[rand_int]
        
        if i % 2 == 0:
          del(team)
          team = PlayerTeam()
          team.add_player(random_player)
        else:
          team.add_player(random_player)
          slots.append(team)
        i += 1

      response = "Doubles bracket randomly generated."
    else:
      for handle in self.presets.get_all():
        user_id = self.__user_ids[handle]
        player = self.__channel_users[user_id]
        if handle == "-bye-":
          del(team)
          team = PlayerTeam()
          slots.append(team)
        elif player.get_handle() == handle:
          if i % 2 == 0:
            del(team)
            team = PlayerTeam()
            team.add_player(player)
          else:
            team.add_player(player)
            slots.append(team)
          i += 1

      slots = self.__get_order_preset(slots)
      response = "Doubles bracket generated from presets."
    
    self.__bracket.generate(slots, is_random)

    return response

  def reset(self, handle):
    '''
    
    '''
    response = ""
    if handle in self.__user_ids:
      user_id = self.__user_ids[handle]
      player = self.__channel_users[user_id]
      games = self.__bracket.get_round_matches()
      match = games[player.get_match_id()]
      response = match.reset_game(user_id)

    if response == "":
      response = "Player not found in tournament."

    return response

  def next(self):
    '''
    Advance the bracket to the next round if all the games are complete.
    '''
    response = ""
    games = self.__bracket.get_round_matches()
    if len(games) == 0:
      response = "The tournament has not started."
    elif self.is_round_complete():
      self.__last_post = None
      response = self.__bracket.advance()
    else:
      response = "The matches are not all complete."

    return response

  def help(self, key):
    # call the readmedocs app
    pass

  def win(self, user):
    '''
    Report a win if the game is not already complete and also
    check for a champion.
    '''
    games = self.__bracket.get_round_matches()
    if len(games) == 0:
      return "The tournament has not started."

    if user == None or user not in self.__channel_users:
      return "Player not found in tournament."

    response = ""
    player = self.__channel_users[user]
    match_id = player.get_match_id()
    if match_id != None:
      match = games[match_id]
      response = match.add_win(user)
    else:
      response = "Player is not in the tournament."

    return response

  def loss(self, user):
    '''
    Report a loss if the game is not already complete 
    '''
  
    games = self.__bracket.get_round_matches()
    if len(games) == 0:
      return "The tournament has not started."

    if user == None or user not in self.__channel_users:
      return "Player not found in tournament."

    response = ""
    player = self.__channel_users[user]
    match_id = player.get_match_id()
    if match_id != None:
      match = games[match_id]
      response = match.add_loss(user)
    else:
      response = "Player is not in the tournament."

    return response

  def clear_users(self):
    self.__channel_users.clear()
    self.__user_ids.clear()
    return "Players have been cleared."

  def destroy(self):
    self.clear_users()
    self.__bracket.destroy()
    self.__last_post = None
    self.participants.clear_users()
    self.presets.clear_users()
    self.is_joinable = False
    
    return "Games have been destroyed"

  def __get_order_preset(self, presets):
    '''
    Flip everyother postion in the list to feed it to tree generator.
    '''
    response = presets
    size = len(response)

    i = 0
    j = 1
    while j < size:
      response[i], response[j] = response[j], response[i]
      i += 2
      j += 2

    response.reverse()
    return response

  def get_printed(self):
    '''
    Loop through the list and print each game.
    '''
    games = self.__bracket.get_round_matches()

    string = ""
    number_of_games = len(games)
    if number_of_games == 0:
      return "The tournament has not started."
    
    champion = False
    if number_of_games == 1 and self.is_round_complete():
      champion = True 

    champ = ""
    for match in games:
      if champion:
        winner = match.get_winner()
        name = winner.get_player_names()
        if name == "":
          name = winner.get_handle()
        if winner.is_single_player():
          champ = "\n" + name + " is the tournament champion!\n"
        else:
          champ = "\n" + name + " are the tournament champions!\n"
        champ += "Grand Prize: :tada: :champagne: :cookie:\n"

      match_number = match.get_match_number()
      if number_of_games == 1:
        if champion:
          string = "%s\n*Match: %d* _Finals_ :trophy:\n" % (string, match_number)
        else:
          string = "%s\n*Match: %d* _Finals_ :trophy:\n" % (string, match_number)
      else:
        string = "%s\n*Match: %d*\n" % (string, match_number)
      string = "%s%s\n" % (string, match.get_score())
    
    return champ + string

  def is_round_complete(self):
    '''
    Check if all the matches in the current round are complete.
    '''
    response = True
    games = self.__bracket.get_round_matches()
    for match in games:
      if match.is_complete() == False:
        response = False

    return response

  def add_participant(self, user_id):
    response = ""
    if user_id in self.__channel_users:
      player = self.__channel_users[user_id]
      response = self.participants.add_user(player.get_handle(), self.get_channel_users())
    else:
      response = "Player not found."

    return response

  def boot_participant(self, user_id):
    response = ""
    if user_id in self.__channel_users:
      player = self.__channel_users[user_id]
      response = self.participants.boot_user(player.get_handle(), self.get_channel_users())
    else:
      response = "Player not found."

    return response

  def list_players(self):
    number_of_players = self.participants.get_count()
    response = "\n*Registered Players ({})*:\n".format(number_of_players)
    if number_of_players == 0:
      response += "None"
    
    for handle in self.participants.get_handles():
      user_id = self.__user_ids[handle]
      player = self.__channel_users[user_id]
      response += player.get_handle_and_name() + "\n"

    return response

  def get_user(self, user_id):
    response = None
    user_upper = user_id.upper()
    if user_upper in self.__channel_users:
      response = self.__channel_users[user_upper]

    return response

  def get_user_id(self, handle):
    response = None
    if handle in self.__user_ids:
      response = self.__user_ids[handle]
      
    return response

  def get_channel_users(self):
    users = []
    for user_id in self.__channel_users:
      users.append(self.__channel_users[user_id])

    return users

  # To-Do: May not need this after creating messanger app, can get matches from db
  def get_round_matches(self):
    return self.__bracket.get_round_matches()