# -*- coding: utf-8 -*-

import qiniu
from django.conf import settings


QINIU = settings.QINIU
auth = qiniu.Auth(QINIU['access_key'], QINIU['secret_key'])


def upload(data, key=None, mime_type='application/octet-stream', bucket=QINIU['bucket_default']):
    if not data:
        return ''
    token = auth.upload_token(bucket, key=key)
    ret, _ = qiniu.put_data(token, key, data, mime_type=mime_type)
    return ret.get('key')


def upload_file_admin(obj, key=None, mime_type='application/octet-stream', bucket=QINIU['bucket_default']):
    # Django Admin Upload
    if not obj.image:
        return ''
    return upload(obj.image.read(), key=key, mime_type=mime_type, bucket=bucket)


def upload_file_req(photo, key=None, mime_type='application/octet-stream', bucket=QINIU['bucket_default']):
    # photo = request.FILES.get('photo', '')
    # <InMemoryUploadedFile: photo.png (image/png)>
    if not photo:
        return ''
    return upload(photo.read(), key=key, mime_type=mime_type, bucket=bucket)


def upload_file_path(path, key=None, mime_type='application/octet-stream', bucket=QINIU['bucket_default']):
    if not path:
        return ''
    token = auth.upload_token(bucket, key=key)
    ret, _ = qiniu.put_file(token, key, path, mime_type=mime_type)
    return ret.get('key')


def qiniu_file_url(key, bucket):
    if not key:
        return ''
    return '{}/{}'.format(QINIU['buckets'][bucket], key)
