import datetime
import io
import os

from PIL import Image, ImageDraw, ImageFont
from urllib import parse
from django.conf import settings
from common.third_party_api.qucloud.clients import cos_client


def watermark_with_text(file_obj,
                        text,
                        prefix,
                        color="black",
                        fontfamily=None):
    image = Image.open(file_obj).convert('RGBA')
    draw = ImageDraw.Draw(image)
    parent_dir = os.path.dirname(os.path.realpath(__file__))
    fontfamily = os.path.join(parent_dir, "NotoSans-Bold.ttf")
    width, height = image.size
    margin = 10
    font = ImageFont.truetype(fontfamily, int(height / 20))
    textWidth, textHeight = draw.textsize(text, font)
    x = (width - textWidth - margin) / 2  # 计算横轴位置
    y = (height - textHeight - margin)  # 计算纵轴位置
    draw.rectangle(
        (x, height - textHeight - margin, x + textWidth, height - margin),
        fill="white")
    draw.text((x, y), text, color, font)
    # file = image.save("image")
    image.show()
    image_bytes = io.BytesIO()
    image.save(image_bytes, format="png")
    image_bytes = image_bytes.getvalue()
    return image_bytes


def download_from_cos(url):
    if url:
        url_item = parse.urlparse(url)
        response = cos_client.get_object(
            Bucket=url_item.netloc.split(".")[0],
            Key=url_item.path)
        local_path = "/".join([settings.UPLOAD_FILE_PATH, url_item.path.split("/")[-1]])
        response['Body'].get_stream_to_file(local_path)
        return local_path
    return None


if __name__ == '__main__':
    with open("picture.jpeg", 'rb') as f:
        image_with_watermark = watermark_with_text(
            f, str(datetime.datetime.now()))
