import os.path
import mimetypes

import filetype
from PIL import Image
from django.conf import settings


def get_file_type(filepath, ft=None):

    ft = filetype.guess(filepath)
    ext = ft.extension

    return ext if ext else 'txt'


def get_filename(name):

    h = hash(name)
    if h < 0:
        h = -h

    return "{}".format(h)


def tailor_image(image_path, points, base_path='.'):
    """以左上角为原点 向右建立x轴 向下建立y轴， 同时截取多张

    :param image: Image obj
    :param point: [(x, y, delta_x, delta_y)]
    :return:
    """

    image = Image.open(image_path)
    heiget = image.height
    width = image.width

    images = []
    for idx, point in enumerate(points):
        if not (width >= point[0] and width >= point[0] + point[2]) or \
                not (heiget >= point[1] and heiget >= point[1] + point[3]):
            continue

        border = (point[0], point[1], point[0] + point[2], point[1] + point[3])
        choice_image = image.crop(border)

        filename = "{}_{}.{}".format(get_filename(image_path), idx, get_file_type(image_path))
        base_dir = os.path.join(settings.DOWNLOAD_IMAGE_PATH)
        if not os.path.exists(base_dir):
            os.makedirs(base_dir)

        file_path = os.path.join(base_dir, filename)
        print(file_path)
        choice_image.save(file_path)
        images.append(file_path)

    return images
