
import time

# from component.Unit import Unit as Unit

from lib.Server.Point import Point as Point

import MatchStatus as MatchStatus
import UserStatus as UserStatus
import ParticipantStatus as ParticipantStatus
import MatchResult as MatchResult

class TurnBasedMatchResource(object):

    def __init__(self):
        self.kind = None
        self.matchId = None
        self.applicationId = None
        self.variant = None
        self.status = None
        self.userMatchStatus = None
        self.participants = None
        self.creationDetails = None
        self.lastUpdateDetails = None
        self.autoMatchingCriteria = None
        self.data = None
        self.results = None
        self.inviterId = None
        self.withParticipantId = None
        self.description = None
        self.pendingParticipantId = None
        self.matchVersion = None
        self.rematchId = None
        self.matchNumber = None
        self.previousMatchData = None

    @classmethod
    def fromstring(cls, match_id, username, hand, draw_pile, discard_pile):
        self = cls()
        self.kind = 'games#turnBasedMatch'
        self.matchId = match_id
        self.applicationId = 'mkw'
        self.variant = 'none'
        self.status = MatchStatus.MatchStatus.MATCH_AUTO_MATCHING
        self.userMatchStatus = UserStatus.UserStatus.USER_TURN
        self.participants = [
                {
                    'kind': 'games#turnBasedMatchParticipant', # always turnBasedMatchParticipant
                    'id': 'player1', # only for the scope of this match
                    'player': { # not populated if autoMatchedPlayer is filled
                        'kind': '',
                        'participantId': username,
                        'avatarImageUrl': None
                    },
                    # 'autoMatchedPlayer': { # not populated if player is filled
                    #     'kind': 'games#autoMatchedPlayer',
                    #     'displayName': None,
                    #     'avatarImageUrl': None
                    # },
                    'autoMatched': False,
                    'status': ParticipantStatus.ParticipantStatus.PARTICIPANT_JOINED
                }
            ]
        self.creationDetails =\
            {
                'kind': 'games#turnBasedMatchModification', # always turnBasedMatchModification
                'participantId': username, # ID of participant that modified match
                'modifiedTimestampMillis': time.time() * 1000 # timestamp at which they modified the match in millisecnds since the epoch in UTC
            }
        self.lastUpdateDetails =\
            {
                'kind': 'games#turnBasedMatchModification', # always turnBasedMatchModification
                'participantId': None, # ID of participant that modified the match
                'modifiedTimestampMillis': None # timestamp at which they modified the match in milliseconds since the epoch in UTC
            }
        self.autoMatchingCriteria =\
            {
                'kind': 'games#turnBasedAutoMatchingCriteria',
                'minAutoMatchingPlayers': 1,
                'maxAutoMatchingPlayers': 1,
                'exclusiveBitmask': None
            }
        self.data =\
            {
                'kind': 'games#turnBasedMatchData',
                'dataAvailable': True, # True if data is available but not reruend in list response, need to query individual match
                'data': { # base64-encoded string with URL_SAFE encoding option
                    'turn': 1,
                    username: {
                        'mana': 1,
                        # 'position': {
                        #     'x': 32,
                        #     'y': 20
                        # },
                        'hand': hand.cards,
                        'draw_pile': draw_pile.cards,
                        'discard_pile': discard_pile.cards,
                        'units': []
                    }
                }
            }
        self.results = None
                #"""[ #participantResult \
                    #{kind, participantId, matchResult, placing}, ... \
                #]"""
        self.inviterId = None
        self.withParticipantId = None
        self.description = 'waiting for match-making...'  # generated by server based on turn state, localized
        self.pendingParticipantId = 'player1'
        self.matchVersion = '0.0.1'
        self.rematchId = None
        self.matchNumber = None
        self.previousMatchData = {}  # games#turnBasedMatchData for the previous match, set during first turn only
        return self

    @classmethod
    def fromdict(cls, d):
        self = cls()
        self.kind = d['kind']
        self.matchId = d['matchId']
        self.applicationId = d['applicationId']
        self.variant = d['variant']
        self.status = d['status']
        self.userMatchStatus = d['userMatchStatus']
        self.participants = d['participants']
        self.creationDetails = d['creationDetails']
        self.lastUpdateDetails = d['lastUpdateDetails']
        self.autoMatchingCriteria = d['autoMatchingCriteria']
        self.data = d['data']
        self.results = d['results']
        self.inviterId = d['inviterId']
        self.withParticipantId = d['withParticipantId']
        self.description = d['description']
        self.pendingParticipantId = d['pendingParticipantId']
        self.matchVersion = d['matchVersion']
        self.rematchId = d['rematchId']
        self.matchNumber = d['matchNumber']
        self.previousMatchData = d['previousMatchData']
        return self

    def change_player_turn(self):
        if self.pendingParticipantId == 'player1':
            self.set_pending_participant_id('player2')
        elif self.pendingParticipantId == 'player2':
            self.set_pending_participant_id('player1')
        else:
            # return jsonify({'success': False, 'errors': {'message': 'unknown participantId'}})
            raise ValueError

    def increment_mana(self, username, i):
        self.data['data'][username]['mana'] += i

    def increment_turn_number(self, i):
        self.data['data']['turn'] += i

    def set_pending_participant_id(self, id):
        self.pendingParticipantId = id

    # def apply(self, username, a):
    #     if a.Type == 'Summon':
    #         u = Unit(a.Id, a.Location)
    #         self.data['data'][username]['units'].append(u.get_json())

    def get_json(self):
        return {
            'kind': self.kind,
            'matchId': self.matchId,
            'applicationId': self.applicationId,
            'variant': self.variant,
            'status': self.status,
            'userMatchStatus': self.userMatchStatus,
            'participants': self.participants,
            'creationDetails': self.creationDetails,
            'lastUpdateDetails': self.lastUpdateDetails,
            'autoMatchingCriteria': self.autoMatchingCriteria,
            'data': self.data,
            'results': self.results,
            'inviterId': self.inviterId,
            'withParticipantId': self.withParticipantId,
            'description': self.description, # generated by server based on turn state, localized
            'pendingParticipantId': self.pendingParticipantId,
            'matchVersion': self.matchVersion,
            'rematchId': self.rematchId,
            'matchNumber': self.matchNumber,
            'previousMatchData': self.previousMatchData # games#turnBasedMatchData for the previous match, set during first turn only
        }
