import json

from Classes.Commands.LogicCommand import LogicCommand
from Classes.Messaging import Messaging
from Database.DatabaseHandler import DatabaseHandler
from Classes.ByteStream import ByteStream
import random
from Classes.Packets.Server.Home.OwnHomeDataMessage import OwnHomeDataMessage


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

    def encode(self, fields):
        pass

    def decode(self, calling_instance):
        fields = {}
        LogicCommand.decode(calling_instance, fields, False)
        fields["NotificationIndex"] = calling_instance.readVInt()
        fields["ChoiceCalendar"] = calling_instance.readVInt()
        LogicCommand.parseFields(fields)
        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
        
        def encodeStarrDrop():        	
        	randomvalue = random.randint(1, 2250)
        	if randomvalue <= 500:
        		a = JSONHandler.RareDropsData
        		fields["Rarity"] = 0
        	elif randomvalue <= 1000:
        		a = JSONHandler.SuperRareDropsData
        		fields["Rarity"] = 1
        	elif randomvalue <= 2000:
        		a = JSONHandler.EpicDropsData
        		fields["Rarity"] = 2
        	elif randomvalue <= 2200:
        		a = JSONHandler.MythicDropsData
        		fields["Rarity"] = 3
        	else:
        		a = JSONHandler.LegendaryDropsData
        		fields["Rarity"] = 4
        	playerData["DropRarity"] = fields["Rarity"]
        	for i in a["DropsData"]:
        		item = random.choice(i["Items"])
        		ItemID = item["ItemID"]       			
        		Fallback = random.randint(item["MinFallback"], item["MaxFallback"])
        		DeliveryID = item["DeliveryID"]
        		DataRef = item["DataRef"]
        		if ItemID == "OwnedPins":
        			RandomItem = random.randint(52, 1000)
        		elif ItemID == "Spyrays":
        			RandomItem = random.randint(17, 191)
        		else:
        			RandomItem = random.randint(12, 100)
        	
        			
        	playerData["GatchaItems"] = {'Boxes': []}
        	box = {'Type': 0, 'Items': []}	
        	item = {'Amount': Fallback, 'DataRef': [DataRef, RandomItem],  'RewardID': DeliveryID}
        	box['Items'].append(item)
        	box['Type'] = 100
        	playerData["GatchaItems"]['Boxes'].append(box)
        	DeprecatedItems = ["OwnedPins", "OwnedThumbnails", "Spyrays"]
        	if ItemID not in DeprecatedItems:
        		SaveList = [] # лист для сохры рандом результата
        		SaveList.append(Fallback) # один рандом результат идет туда
        		playerData[ItemID] += SaveList[0] # добавление первого элемента листа к сумме валюты
        		SaveList.clear() # очистка листа для следующей работы
        	else:
        		SaveList = []
        		SaveList.append(RandomItem)
        		playerData[ItemID].append(SaveList[0])
        		SaveList.clear()
        		
        def createStarrDropOpening(amount):
        	encodeStarrDrop()
        	for i in ShopData["Offers"]:
        		if fields["OfferIndex"] == ShopData["Offers"].index(i):
        			playerData["PurchasedOffers"].append(ShopData["Offers"].index(i)) 	
        	for i in range(amount):
        		db_instance.updatePlayerData(playerData, calling_instance)
        		fields["Socket"] = calling_instance.client
        		fields["Command"] = {"ID": 228}
        		fields["PlayerID"] = calling_instance.player.ID
        		fields["StarrDrops"] = True
        		fields["Offer"] = fields["OfferIndex"]
        		Messaging.sendMessage(24111, fields, cryptoInit) 
        		fields["Socket"] = calling_instance.client
        		fields["Command"] = {"ID": 203}
        		fields["StarrDrops"] = True
        		fields["PlayerID"] = calling_instance.player.ID
        		Messaging.sendMessage(24111, fields, cryptoInit)
        		fields["Socket"] = calling_instance.client
        		fields["Command"] = {"ID": 228}
        		fields["PlayerID"] = calling_instance.player.ID
        		fields["StarrDrops"] = False
        		fields["Offer"] = fields["OfferIndex"]
        		Messaging.sendMessage(24111, fields, cryptoInit)
        		
        		
        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 == "ChromaCredits":
        		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 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 appendNotification(notification):
        	playerData["SeenNotifications"].append(notification)
        	
        	
        for i in playerData["Notifications"]:
        	if fields["NotificationIndex"] == playerData["Notifications"].index(i):
        		AppendableItems = [25, 19]
        		if i["RewardType"] in AppendableItems:
        			giveDeliveryVanity(i["ItemName"], 1, i["Extra"])
        			
        		elif i["RewardType"] == 3:
        			giveDeliveryBrawler(i["Brawler"], i["BrawlerCard"], i["BrawlerPower"])
        		elif i["RewardType"] == 4:
        			giveDeliverySkin(i["Extra"])
        		elif i["RewardType"] == 49:
        				createStarrDropOpening(i["Extra"], i["Amount"])
        		else:
        			giveDeliveryResources(i["ItemName"], i["Amount"])
        		i["Readed"] = True
        		if i["StarrDrops"] == True:
        			clearBox()
        		else:
        			sendCommand(203)
        			clearBox()
        			
        if fields["NotificationIndex"] == 0:
        	giveDeliveryResources("Gems", 170)
        	appendNotification(0)
        	sendCommand(203)
        	clearBox()


    def getCommandType(self):
        return 528