class DeleteBetResponse(Response):

    def __init__(self, client):
        Response.__init__(self, client)
        self.data = Data()
        self.__idx = int(client.arg('idx'))
        self.__row = int(client.arg('row'))
        self.__user = client.arg('user')
        self.__msg = '%s: match %d: delete bet for \'%s\'' % (self.get_user(), self.__idx, self.__user)


    def html(self):
        if self.get_user() == 'anonym':
            return []

        self.data.load()

        match = self.data.get_matches_section()[self.__idx]

        if 'bets' in match and self.__row <= len(match['bets']):
            bet = match['bets'][self.__row-1]
            if self.__user == bet['user']:
                match['bets'].pop(self.__row-1)
                self.data.save()
                self.data.commit(self.__msg)
            else:
                sys.stderr.write('could not delete "%s" - found "%s" instead.' % (self.__user, bet['user']))

        return []
class AddResultResponse(Response):

    def __init__(self, client):
        Response.__init__(self, client)
        self.data = Data()
        self.__idx = int(client.arg('idx'))
        self.__betdata = client.arg('data')
        self.__msg = "%s: match %d: set result" % (self.get_user(), self.__idx)


    def html(self):
        if self.get_user() == 'anonym':
            return []

        self.data.load()

        try:
            betdata = json.loads(self.__betdata)
        except:
            raise ValueError('Value of __betdata ("%s") can not be parsed.' % self.__betdata)

        formvalue = betdata['result']
        if formvalue.count('|') > formvalue.count(','):
            betinfo = formvalue.split('|')
        else:
            betinfo = formvalue.split(',')

        matches = self.data.get_matches_section()
        match = matches[self.__idx]

        fulltime = betinfo[0]
        halftime = betinfo[1]
        goals = betinfo[2:]

        for idx, goalee in enumerate(goals):
            goals[idx] = self.data.get_playerid(goalee)

        match['result'] = fulltime
        match['halftime'] = halftime
        match['goals'] = goals

        self.data.save()
        self.data.commit(self.__msg)

        return [u'<html></html>']
class AddMatchResponse(Response):

    def __init__(self, client):
        Response.__init__(self, client)
        self.data = Data()
        self.__matchdata = urllib.unquote(client.arg('data'))
        self.__msg = "%s: main: add match" % self.get_user()


    def html(self):
        if self.get_user() == 'anonym':
            return []

        self.data.load()

        try:
            matchdata = json.loads(self.__matchdata)
        except:
            raise ValueError('Value of __matchdata ("%s") can not be parsed.' % self.__matchdata)

        formvalue = matchdata['match']

        matchname, matchdate = formvalue.split(u' 20', 2)
        matchdate = u'20%s' % matchdate
        hometeam, awayteam = matchname.split(u' - ', 2)

        teams = self.data.get_teams_section()
        if not hometeam in teams:
            sys.stderr.write("error: hometeam (%s) not in teams" % hometeam)
            return []

        if not awayteam in teams:
            sys.stderr.write("error: awayteam (%s) not in teams" % awayteam)
            return []

        matchname = u'%s - %s' % (hometeam, awayteam)

        newmatch = {}
        newmatch['game'] = matchname
        newmatch['date'] = matchdate

        matches = self.data.get_matches_section()

        idx = 1
        inserted = False
        while idx < len(matches):
            match = matches[idx]
            date = match['date']
            if date[:10] > matchdate[:10]:
                matches.insert(idx, newmatch)
                inserted = True
                self.__msg = "%s: main: insert match at index %d" % (self.get_user(), idx)
                break
            idx += 1

        if not inserted:
            self.__msg = "%s: main: expanded list of matches" % self.get_user()
            matches.append(newmatch)

        self.data.save()
        self.data.commit(self.__msg)

        return []