import json
from subprocess import call
from datetime import datetime
import copy
import time

from Classes.Commands.LogicCommand import LogicCommand
from Classes.Messaging import Messaging
from Database.DatabaseHandler import DatabaseHandler

from JSON.JSONHandler import JSONHandler

class LogicDailyLoginCommand(LogicCommand):
    def __init__(self, commandData):
        super().__init__(commandData)

    def encode(self, fields):
        return self.messagePayload

    def decode(self, calling_instance):
        fields = {}
        calling_instance.readVInt()
        calling_instance.readVInt()
        calling_instance.readVInt()
        calling_instance.readVInt()
        fields["GiftID"] = calling_instance.readVInt()
        fields["Choice"] = calling_instance.readVInt()
        fields["Choice1"] = calling_instance.readVInt()
        return fields

    def execute(self, calling_instance, fields, cryptoInit):
        db_instance = DatabaseHandler()
        playerData = json.loads(db_instance.getPlayerEntry(calling_instance.player.ID)[2])
        
        fields["IsBrawlPassReward"] = False
        
        LoginData = JSONHandler.LoginData
        
        box = {'Type': 100, 'Items': []}
        boxVanity = {'Type': 100, 'Items': []}
        
        def giveDeliveryResources(type, amount):
        	playerData[type] += amount
        	if type == "Coins":
        		boxType = 7
        	if type == "Gems":
        		boxType = 8
        	if type == "Bling":
        		boxType = 25
        	if type == "RecruitTokens":
        		boxType = 22
        	if type == "ChromaticCoins":
        		boxType = 23
        	if type == "PowerPoints":
        		boxType = 24
        	playerData["GatchaItems"] = {'Boxes': []}	
        	item = {'Amount': amount, 'DataRef': [0, 0],  'RewardID': boxType}
        	box['Items'].append(item)
        	playerData["GatchaItems"]['Boxes'].append(box)
        
        def giveDeliveryVanity(type, amount, skin):
        	playerData[type].append(skin)
        	if type == "OwnedPins":
        		boxType = 52
        	if type == "OwnedThumbnails":
        		boxType = 28
        	playerData["GatchaItems"] = {'Boxes': []}
        		
        	item = {'Amount': amount, 'DataRef': [boxType, skin],  'RewardID': 11}
        	boxVanity['Items'].append(item)
        	if len(box["Items"]) != 0:
        		playerData["GatchaItems"]['Boxes'].append(box)
        	playerData["GatchaItems"]['Boxes'].append(boxVanity)
        	
        def giveDeliverySkin(skin):
        	playerData["OwnedSkins"].append(skin)
        	playerData["GatchaItems"] = {'Boxes': []}	
        	item = {'Amount': 1, 'DataRef': [29, skin],  'RewardID': 9}
        	box['Items'].append(item)
        	playerData["GatchaItems"]['Boxes'].append(box)
        
        def giveDeliveryBrawler(brawler, card, powerlevel):
        	playerData["OwnedBrawlers"][brawler] = {'CardID': card, 'Skins': [0], 'Trophies': 0, 'HighestTrophies': 0, 'PowerLevel': powerlevel, 'PowerPoints': 0, 'State': 2, 'MasteryPoints': 0, 'MasteryTier': 0}
        	playerData["GatchaItems"] = {'Boxes': []}	
        	item = {'Amount': 1, 'DataRef': [16, brawler],  'RewardID': 1}
        	box['Items'].append(item)
        	playerData["GatchaItems"]['Boxes'].append(box)
        	
        def changeResourceNegative(resource, amount):
        	playerData[resource] -= amount
        	
        def addDay():
        	playerData["ClaimedLoginRewardIndex"] += 1
        	        
        def sendCommand(command):
        	db_instance.updatePlayerData(playerData, calling_instance)
        	if command == 203:
        		fields["StarrDrops"] = False
        	else:
        		pass
        	fields["Socket"] = calling_instance.client
        	fields["Command"] = {"ID": command}
        	fields["PlayerID"] = calling_instance.player.ID
        	Messaging.sendMessage(24111, fields, cryptoInit)       	        	
        	
        def clearBox():
        	box['Items'].clear()
        	boxVanity['Items'].clear()
        	
        def specializeResource(intType, amount):
        	if intType == 1:
        		resource = "Coins"
        	elif intType == 16:
        		resource = "Gems"
        	elif intType == 45:
        		resource = "Bling"
        	elif intType == 38:
        		resource = "RecruitTokens"
        	elif intType == 39:
        		resource = "ChromaticCoins"
        	elif intType == 41:
        		resource = "PowerPoints"
        	giveDeliveryResources(resource, amount)
        	
        def specializeVanity(intType, amount, extra):
        	if intType == 19:
        		vanity = "OwnedPins"
        	elif intType == 25:
        		vanity = "OwnedThumbnails"
        	giveDeliveryVanity(vanity, amount, extra)
        

        	
        
        for i in LoginData["LoginItems"]:
            if fields["GiftID"] == i["Day"] and fields["GiftID"] != 6:
            	
            	for reward in i["Rewards"]:
            		if reward["ItemType"] == 19 or reward["ItemType"] == 25:
            			specializeVanity(reward["ItemType"], 1, reward["Extra"])
            		elif reward["ItemType"] == 4:
            			giveDeliverySkin(reward["Extra"])
            		else:
            			specializeResource(reward["ItemType"], reward["Amount"])
            			
            	addDay()
            	sendCommand(203)
            	clearBox()
        
        if fields["GiftID"] == 6:
        	specializeResource(45, 2750)
        	addDay()
        	sendCommand(203)
        	clearBox()
        
            	
            	
            	
        		
        		
   
    		
    	
    def getCommandType(self):
        return 550