import csv
from datetime import datetime
import sys
import os
from discord_webhook import DiscordWebhook


webhook = DiscordWebhook(
    url='https://discordapp.com/api/webhooks/744608404848246926/FwwWUNmuWsCetFDBOcA1trCx6nSflI0yX3f9BNh7-oB5a2VYSLl882di23XK2TNWwQxP',
    username="billing vfgdsp")

dirpath = "."
FILE = [filename for filename in os.listdir(dirpath) if filename.startswith("TMGDSP_")]
FILE = FILE[0]
ext_date_from_filaname = FILE.split('_')[-1]
print(ext_date_from_filaname)





#usrmonth = input("Month to be processed: ")

countofnotsms = int(1)


dictionary = {}

def add_dict(id, key, value):
    dict = dictionary.get(id)
    if key in dict:
        print("increasing notsms dict key for: ",value,"key IS: ",key)
        dict[key] += value

        print("end state: ",dict[key])
        dict[key] = round(dict[key],5)
        print("key: ",key)


    else:
        print("Never should happen", id)

def add_dictsms(id, pricesms):
    dict = dictionary.get(id)

    print("increasing sms dict key for dict: ",dict," for :",pricesms)
    dict["smscount"] += pricesms

def add_dictdataamount(id, dataamount):
    dict = dictionary.get(id)
    print("increasing dataamount dict key for dict: ",dict," for :",dataamount)
    dict["dataamount"] += int(dataamount)/1024




#MAIN
with open(FILE, newline='', encoding='utf-8') as csvfile:
    reader = csv.DictReader(csvfile, delimiter=';')
    for row in reader:

        #print(row)
        if row['MSISDN'] == '': 
            continue #skip empty MSISDN

        #if row['BILLED_PERIOD_START'] == '':
            #continue

        #my_string = row['BILLED_PERIOD_START']
        #my_string = '2021-09-06'
        #print(my_string)
        #try:
            #my_date = datetime.strptime(my_string, "%Y-%m-%d")
        #except:
            #print("An exception occurred, current my_string is: ", my_string)
            #sys.exit(1)

        #print(row['BILLED_PERIOD_START'])
        #print(my_date.month)
        
        
        
         #if my_date.month != '5':
             #continue #skip bad dates



        MSISDN = int(row['MSISDN'])
        ICCID = int(row['ICCID'])
        IMSI = int(row['IMSI'])


        print("charge_net: ",row['CHARGE_NET'])
        price = float(row['CHARGE_NET'].replace(',','.'))
        

        print("before conditions price: ",price, "for: ",ICCID)

        typ = None
        if row['CHARGE_TYPE'] == "Pravidelné měsíční poplatky":
            typ = "data"
        elif row['CHARGE_TYPE'] == "Poplatky za roamingový datový provoz":
            typ = "data"
        elif row['CHARGE_TYPE'] == "Poplatky za národní datový provoz":
            typ = "data"
        elif row['CHARGE_TYPE'] == "Poplatky za roamingový SMS provoz":
            typ = "sms"
        elif row['CHARGE_TYPE'] == "Poplatky za národní SMS provoz":
            typ = "sms"
        else:
            typ = 'other'


        if row['INCREMENT'] == "SMS":

            pricesms = int(row['RATED_AMOUNT'])
        else:
            pricesms = 0

        #only if not exist create new record in dictionary for ID
        if not MSISDN in dictionary:

            dictionary[MSISDN] = {'IMSI':IMSI, 'ICCID':ICCID,'data':0.00000, 'sms':0.00000, 'other':0.00000, 'dataamount':0, 'smscount':pricesms}
            print("Creating new dictionary: ", dictionary[MSISDN])
            if dictionary[MSISDN] == "436761890300016":
                print("creating dictionary for our unit")
                input()


        print("Adding: ", price, " for: ", dictionary[MSISDN], "TYP: ",typ)
        add_dict(MSISDN, typ, price)
        if MSISDN == 436761890301205:
            print("created dictionary for our unit")



        if row['INCREMENT'] == "SMS":
            print("pricesms: ",pricesms," for unit: ",dictionary[MSISDN])
            add_dictsms(MSISDN, pricesms)
        if MSISDN == 436761890301205:
            print("increasing pricesms")


        if row['INCREMENT'] == "1/1 kB":

            if row['RATED_AMOUNT'] != "0":

                dataamount = row['RATED_AMOUNT']

                print(dataamount)
                add_dictdataamount(MSISDN, dataamount)
            else:
                dataamount = 0



    #ptry:
        #print(dictionary[436761890319959]) #one with both types
    #pexcept:
        #pprint("Required unit is not in our set")
        #psys.exit(1)

#pprint(len(dictionary.keys()))

#for key, value in dictionary.items():
   #print(key, ' : ', value)


print("Count of units: ", len(dictionary.keys()))
#print("Count of sms: ",countofsms)
#for dict_value in dictionary:
#    type(dict_value)
#    #for k, v in dict_value.items():
     

#with open('fakturace_tmgdsp_export_20211110v2.csv', 'w') as f:
#   for key in dictionary.keys():
#      print(key,dictionary[key])
#      f.write("%s,%s\n"%(key,dictionary[key]))


with open('output_TMGDSP_'+ext_date_from_filaname, 'w') as f:

    writer = csv.writer(f)
    writer.writerow(["MSISDN","ICCID","IMSI","DATA-PRICE","DATA-AMOUNT","SMS-PRICE","SMS-COUNT","OTHER-PRICE","SIM-STATUS"])
    for key in dictionary.keys():
        # Getting all required variables to write them into export

        MSISDN = key
        ICCID = dictionary[key]['ICCID']
        IMSI = dictionary[key]['IMSI']
        data_price = dictionary[key]['data']
        sms_price = dictionary[key]['sms']
        other_price = dictionary[key]['other']
        sms_count = dictionary[key]['smscount']
        data_amount = dictionary[key]['dataamount']



        print("MSISDN: ", MSISDN)
        print("ICCID: ", ICCID)
        print("IMSI: ", IMSI)
        print("data_price: ", data_price)
        print("sms_price: ", sms_price)
        print("sms_count: ", sms_count)
        writer.writerow([MSISDN, ICCID, IMSI, data_price, data_amount, sms_price, sms_count, other_price, "N/A"])

csvfile.close()


with open('output_TMGDSP_'+ext_date_from_filaname, "rb") as f:
    webhook.add_file(file=f.read(), filename='output_TMGDSP_'+ext_date_from_filaname)

response = webhook.execute()



#csv_columns = ['takhleuztoneudelam', 'ICCID', 'data', 'sms', 'other', 'smscount']
#try:
#    with open('output_tmgdsp_202112.csv', 'w') as csvfile:
#        w = csv.DictWriter(sys.stdout, csv_columns)
            #        for key, val in sorted(dictionary.items()):
            #row = {'takhleuztoneudelam': key}
            #row.update(val)

            #writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
            #writer.writerow(row)

#except IOError:
    #print(f"I/O error: {IOError}")
#csvfile.close()
