import requests
import json
import hashlib

URL = 'https://paste.opendev.org/json/'
NAME = 'opendev'

def get_service_tag():
    return NAME

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

        # create JSON payload for new paste
        payload = {
            'language': 'text',
            'code': content,
            'private': False
            #'expire': '1day'
        }

        # send request to create new paste
        response = requests.post(URL + '?method=pastes.newPaste', json=payload)

        status = response.status_code
        paste_id = response.json()['data']

        if status == 200:
            #print(f'JSON object uploaded to dpaste.com: {dpaste_url}')
            md5sum = hashlib.md5(content.encode('utf-8')).hexdigest()

            return {
                'service': NAME,
                'key': URL[:-6],
                'md5sum': md5sum,
                'name':  NAME + '_' + paste_id + '_' + md5sum[:5]
            }
        else:
            return None
    except requests.exceptions.RequestException:
        return None
# we can get the paste back by:
## $ > curl -d '{"paste_id":819463}' -H 'Content-Type: application/json' https://paste.opendev.org/json/?method=pastes.getPaste  |jq .data.code
