import random
import string
import csv
import argparse
import requests
import sys
import os

try:
    from faker import Faker
except ImportError:
    print("Missing dependency faker: <https://pypi.org/project/Faker/>. Please install it with `pip install Faker`.")
    sys.exit(1)

try:
    import requests
except ImportError:
    print("Missing dependency requests: <https://requests.readthedocs.io/en/master/>. Please install it with `pip install requests`.")
    sys.exit(1)

requests.packages.urllib3.disable_warnings()


# generate a csv file containing 100 entries of PII data
def csv_generator(filename, fake):
    if sys.version_info[0] == 2:
        csvfile = open(filename, 'w')
    else:
        csvfile = open(filename, 'w', newline='')
    fieldnames = ['last name', 'first name', 'title', 'telephone number', 'street address', 'city', 'state', 'postal code', 'email', 'social security number']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for _ in range(100):
        writer.writerow({'last name':fake.last_name(),'first name':fake.first_name(), 'title':fake.prefix(), 'telephone number':fake.phone_number(), 'street address':fake.street_address(), 'city':fake.city(), 'state':fake.state(), 'postal code':fake.postcode(), 'email':fake.email(), 'social security number':fake.ssn()})
    csvfile.close()


def csv_uploader(filepath, url):
    try:
        files = {'file': open(filepath,'rb')}
        requests.post(url, files=files,verify=False)
        print("upload succeeded")
    except:
        print("upload failed")


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="HTTP Upload of PII Data emulation")
    parser.add_argument("-url", help = "the url where the csv will be uploaded to", required=True)
    parser.add_argument("-f", help="the filename of the generated csv, without the extention 'csv'", required=False)
    args = parser.parse_args()
    
    if args.f:
        if os.path.exists(args.f):
            filepath = args.f
            filename = os.path.basename(filepath)
    else:
        filepath = filename = (''.join(random.choice(string.ascii_letters) for i in range(8)))+'.csv'
        fake = Faker('en_US')
        csv_generator(filename,fake)

    csv_uploader(filepath, args.url)
