import base64
import io
import os
import random
import string

import boto3
from PIL import Image

from ticket.bucket import RASADYAR_ENDPOINT, RASADYAR_BUCKET_NAME, RASADYAR_ACCESS_KEY, RASADYAR_SECRET_KEY

ARVAN_TICKET_GALLERY = "https://profileimagedefault.s3.ir-thr-at1.arvanstorage.ir/"
# ARVAN_TICKET_GALLERY = "https://ticketgallery.s3.ir-thr-at1.arvanstorage.com/"
ARVAN_User_Image_URL = 'https://profileimagedefault.s3.ir-thr-at1.arvanstorage.ir/'


def send_image_to_server(image):
    ran = ''.join(random.choices(string.ascii_uppercase + string.digits, k=15))
    imgdata = base64.b64decode(image)
    img = Image.open(io.BytesIO(imgdata))

    img.thumbnail((500, 500))

    buffer = io.BytesIO()
    img.save(buffer, format="PNG")
    buffer.seek(0)

    s3_resource = boto3.resource(
        's3',
        endpoint_url=RASADYAR_ENDPOINT,
        aws_access_key_id=RASADYAR_ACCESS_KEY,
        aws_secret_access_key=RASADYAR_SECRET_KEY
    )

    bucket = s3_resource.Bucket(RASADYAR_BUCKET_NAME)
    bucket.put_object(
        ACL='public-read',
        Body=buffer,
        Key=ran + '.jpg',
        ContentType='image/png'
    )

    image_url = f"{RASADYAR_ENDPOINT}/{RASADYAR_BUCKET_NAME}/{ran + '.jpg'}"

    return image_url


def upload_listed_image(req=None, field=None):
    image_list = []
    if req.data[field] != []:
        for item in req.data[field]:
            image_list.append(send_image_to_server(item))
        req.data.pop(field)
        req.data[field] = image_list
    elif req.data[field] == "":
        req.data[field] = "empty"
    return req


def send_image_to_server_for_poultry_science(image, name):
    s3 = boto3.client(
        's3',
        endpoint_url=RASADYAR_ENDPOINT,
        aws_access_key_id=RASADYAR_ACCESS_KEY,
        aws_secret_access_key=RASADYAR_SECRET_KEY
    )

    s3.upload_fileobj(
        image,
        RASADYAR_BUCKET_NAME,
        name,
        ExtraArgs={'ACL': 'public-read'}  # دسترسی عمومی
    )

    return f"{RASADYAR_ENDPOINT}/{RASADYAR_BUCKET_NAME}/{name}"
