from cStringIO import StringIO
from base64 import b64encode

import requests

from .. import config


def post_from_path(image, caption=None):
    image_file = open(image, 'r')
    return post_from_file(image_file)


def post_from_file(image_file, caption=None):
    data = b64encode(image_file.read())
    return post_b64_data(data, caption)


def post_from_pil(image, caption=None):
    output = StringIO()
    image.save(output, format="PNG")
    output.seek(0)
    return post_from_file(output, caption)


def post_string_data(data, caption=None):
    b64_data = b64encode(data)
    return post_b64_data(b64_data, caption)


def post_b64_data(b64_data, caption=None):
    if caption is None:
        caption = "Autogenerated by a horse..."

    payload = {
        'album_id': None,
        'image': b64_data,
        'title': caption,
        'description': None
    }

    resp = requests.post(
        "https://api.imgur.com/3/image",
        data=payload,
        headers={
            "Authorization": "Client-ID {0}".format(config.IMGUR_API_TOKEN)
        }
    )
    return resp.json()['data']['link']
