import datetime
from io import BytesIO
import discord
from discord import message
from discord.ext import commands
import json
import time
import itertools 
from datetime import time, date
import os
from discord.ext.commands.core import has_any_role, has_role
import httpx
import asyncio

bot = commands.Bot(command_prefix='NB!', description='RDI Stock', reconnect=True)

headers = {'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTUsImlhdCI6MTY2MjMyNTY5MCwiZXhwIjoyNjc1OTE3NjkwfQ.FSfDeMq3AHKUQmUVqCT2QV6cSLIL92nAkxs2128s8CU'}
tokenw = 'ODkxMDg1MjU5NzQyMDE1NDg4.YU5N0Q.9jnL4Qi0j7Jr49z_JhWTOjwkeTQ'

@bot.remove_command('help')

@bot.event
async def on_ready():

    print('Bot logged in.')

@bot.command()
@commands.has_permissions(administrator=True) 
async def keys(ctx):
    w = httpx.get(f'http://localhost:5000/orders/keys-sold', headers=headers)
    info = w.json()
    embed = discord.Embed(
        title='**Keys Sold This Week**',
        color=0x000000,
        description=f"Total Keys Sold This Week: **{info['thisWeeksOrders']}**"
    )
    embed.set_footer(text='Made By Rad (incompetent faggot)')
    embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/718534646262005902/726519805292838922/logo_1.jpg')
    embed.timestamp = datetime.datetime.utcnow()
    for keys in info['thisWeeksKeys']:
       #print(keys)


        cat_stock = []
        stock = (info['thisWeeksKeys'][f'{keys}'])
        
        for items in info['thisWeeksKeys'][f'{keys}']:# this should print out the key variaint

            stuff = (info['thisWeeksKeys'][f'{keys}'][f'{items}'])# this shows the amount of keys sold.

            h = ': '
            cat_stock.append(items + h + f'**{stuff}**' + '\n' )
        #cat_stock.append(str(stock) + '\n')
        cat_stoc2k = "".join(cat_stock)

        #print(cat_stoc2k)
        embed.add_field(name=f"{keys}", value=f"{cat_stoc2k}", inline=True)
        
    await ctx.send(embed=embed)
    #print(w.json())

global milly

@bot.command()
async def changeprice(ctx, menu, variant, value: int):
    if ctx.author.id == 859838138931216395 or ctx.author.id == 775838073845317655:
        json_object["d"] = 100

        a_file = open("sample_file.json", "w")
        json.dump(json_object, a_file)
        a_file.close()

@bot.command()
async def check(ctx):
    if ctx.author.id == 859838138931216395 or ctx.author.id == 775838073845317655:

        embed = discord.Embed(
            title='**Keys reselling prices.**',
            color=0x000000,
            description=f"This price keys were bought at reseller prices.**"
        )
        embed.set_footer(text='Made By Rad (incompetent faggot)')
        embed.set_thumbnail(
            url='https://cdn.discordapp.com/attachments/718534646262005902/726519805292838922/logo_1.jpg')
        embed.timestamp = datetime.datetime.utcnow()

        f = open('config.json', "r")
        data = json.loads(f.read())

        for i in data:
            cat_stock = []
            #print(i)
            for o in data[i]:# i = Menu # o = variant # e = reseller price

                e = (data[i][o])
               # print(i, o, e)
                h = ': **$'
                cat_stock.append(str(o) + str(h) + f"{e}**" + '\n')


            cat_stoc2k = "".join(cat_stock)
            embed.add_field(name=f"{i}", value=f"{cat_stoc2k}", inline=True)
        # Closing file
        f.close()
        await ctx.send(embed=embed)


@bot.command()
async def money(ctx):
    with open('config.json') as f:
        c = json.load(f)
    t = c.get('Impulse Mod Menu')
    wr3 = t.get('Standard')
    print(wr3)
    global assburger
    
    print(ctx.author.id)
    if ctx.author.id == 859838138931216395 or ctx.author.id == 775838073845317655:
        w = httpx.get(f'http://localhost:5000/orders/keys-sold', headers=headers)
        info = w.json()
        #print(info)
        embed = discord.Embed(
            title='**Money Made This Week**',
            color=0x000000,
            description=f"---------Total Money Made This Week: **${info['thisWeekEarned']}**---------"
        )
        embed.set_footer(text='Made By Rad (incompetent faggot)')
        embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/718534646262005902/726519805292838922/logo_1.jpg')
        embed.timestamp = datetime.datetime.utcnow()
        global grossprofit
        
        
        for keys in info['thisWeeksKeysEarned']: # This should print the brand.




            cat_stock = []
            grossprofit = []#
            netprofy = []#
            keysold = []

            stock = (info['thisWeeksKeysEarned'][f'{keys}'])
            
            for items in info['thisWeeksKeysEarned'][f'{keys}']:# this should print out the key variaint
                brand = c.get(f'{keys}')
                w = brand.get(f'{items}')# reseller keys price.
                inf = info['thisWeeksKeys'][f'{keys}'][f'{items}']# how many keys were sold

                global milly
                keysvprice = (int(info['thisWeeksKeys'][f'{keys}'][f'{items}']) * int(w))# how many keys were sold X (Times) reseller price keys were bought at, Total net profit of key.
                milly = int(info['productVariantPrices'][f'{keys}'][f'{items}']) * int(info['thisWeeksKeys'][f'{keys}'][f'{items}'])
              #  milly = (int(info['thisWeeksKeysEarned'][f'{keys}'][f'{items}']) - keysvprice)# how much profit key made? | This is wrong it should be how many keys were sold * price keys were sold
                #print(keys, items, inf, w, milly)
                grossprofit.append(milly)
                netprofy.append(keysvprice)
                keysold.append(int(info['thisWeeksKeys'][f'{keys}'][f'{items}']))
                stuff = (info['thisWeeksKeysEarned'][f'{keys}'][f'{items}'])
                h = ': **$'

                cat_stock.append(items + h + f'{milly}**' + '\n')
               # global assburger
                assburger = (sum(grossprofit) - sum(netprofy))
            cat_stoc2k = "".join(cat_stock)


            embed.add_field(name=f"{keys}", value=f"{cat_stoc2k} \n __KEPU__: **${sum(netprofy)}**\n __Total Gross__: **${sum(grossprofit)}** \n __Total Keys Sold__: **{sum(keysold)}** \n __Total Net Profit__: **${assburger}**", inline=True)


        await ctx.send(embed=embed)
    else:
        print(ctx.author.id)
        print('mf really tried.')
@bot.command()
@commands.has_role(839642425349373952)
async def gdm(ctx, user:discord.User):
    
    while True:
        w = httpx.get('http://localhost:5000/products/stock', headers=headers)
        
        embed = discord.Embed(
            color=0x000000,
            description='__RDI STOCK__',)
        embed.set_footer(text='Made By Rad (incompetent faggot)')
        embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/718534646262005902/726519805292838922/logo_1.jpg')
        embed.timestamp = datetime.datetime.utcnow()
        
        for items in w.json():
            cat_stock = []
            cat = w.json()[f'{items}']
            for subcats in cat:
                stock = (w.json()[f'{items}'][f'{subcats}'])
                hy = ': '
                cat_stock.append(subcats + hy + str(stock) + '\n')
            string_version = "".join(cat_stock)
            embed.add_field(name=f"{items}", value=f"{string_version}", inline=True)

        await user.send(embed=embed)
        await asyncio.sleep(21600)


# @bot.command()
# @commands.me
# async def dm(ctx, user: discord.User, message):
#     await user.send(message)

        

@bot.command()
@commands.has_role(839642425349373952)
async def stock(ctx, choice=None):
    w = httpx.get('http://localhost:5000/products/stock', headers=headers)
    
    embed = discord.Embed(
        color=0x000000,
        title='Real Dudes Inc'
    )
    embed.set_footer(text='Made By Rad (incompetent faggot)')
    embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/718534646262005902/726519805292838922/logo_1.jpg')
    embed.timestamp = datetime.datetime.utcnow()
    
    for items in w.json():
        print(items)
        cat_stock = []
        cat = w.json()[f'{items}']
        for subcats in cat:
            stock = (w.json()[f'{items}'][f'{subcats}'])
            #print(subcats)
            hy = ' : '
            cat_stock.append(subcats + hy + str(stock) + '\n')
        string_version = "".join(cat_stock)
        embed.add_field(name=f"{items}", value=f"{string_version}", inline=True)
          

    await ctx.send(embed=embed)

@bot.command()
@commands.has_role(839642425349373952)
async def csv(ctx, choice=None):
    w = httpx.get('http://localhost:5000/orders/csv?start='+choice, headers=headers)
    f = BytesIO(bytes(w.text,'ascii'))
    await ctx.send('ඞ', file=discord.File(f,'sales.csv'))


@bot.command()
@commands.has_role(839642425349373952)
async def order(ctx, order: int, date=None):
    if date == None:
        date = "new"
    elif date == 'Old':
        date = 'old'
    elif date == 'New':
        date = "new"
    
    info = httpx.get(f'http://localhost:5000/orders/all/{order}', headers=headers)
    
    embed = discord.Embed(color=0x000000,title=f'**Order ID** __#{order}__ **Info.**',description=f'Showing order from {date.title()} site')
    embed.set_footer(text='Made By Rad (incompetent faggot)')
    embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/718534646262005902/726519805292838922/logo_1.jpg')
    embed.timestamp = datetime.datetime.utcnow()

    try:
        embed.add_field(name="__Username__", value=f"{info.json()[f'{date}']['user']['username']}", inline=True)
        embed.add_field(name="__Payment Method__", value=f"{info.json()[f'{date}']['paymentMethod']}", inline=True)
        embed.add_field(name="__Total Amount__", value=f"{info.json()[f'{date}']['total']}", inline=True)
        embed.add_field(name="__Key Type__", value=f"{info.json()[f'{date}']['keys'][0]['product']['title']}", inline=True)
        embed.add_field(name="__Creation Date__", value=f"{info.json()[f'{date}']['created_at']}", inline=True)
        embed.add_field(name="__Invoice ID__", value=f"{info.json()[f'{date}']['invoiceId']}", inline=True)
        embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url)
        
    except Exception as e:
        await ctx.send('Full information may not show because of product being deleted or not existing.')
        pass
        print(e)

    await ctx.send(embed=embed)
bot.run(tokenw) 
