import hashlib
import json
import requests

NAME = 'dpaste'

def get_service_tag():
    return NAME

def upload(data):
    try:
        content = json.dumps(data)
        syntax = 'json'
        expiry_days = ''

        r = requests.post('https://dpaste.com/api/v2/',
                          data={'content': content,
                                'syntax': syntax,
                                'expiry_days': expiry_days},
                          headers={'User-Agent': 'My Python Project'})

        if r.status_code == 201:
            dpaste_url = r.headers['Location']
            #print(f'JSON object uploaded to dpaste.com: {dpaste_url}')
            md5sum = hashlib.md5(content.encode('utf-8')).hexdigest()

            return {
                'service': NAME,
                'key': dpaste_url,
                'md5sum': md5sum,
                'name':  NAME + '_' + dpaste_url.rsplit('/', 1)[-1]
            }
        else:
            return None
    except requests.exceptions.RequestException:
        return None

