import itertools
import re

from PIL import Image, ImageChops, ImageFilter
from easy_thumbnails import utils


def _compare_entropy(start_slice, end_slice, slice, difference):
    """
    Calculate the entropy of two slices (from the start and end of an axis),
    returning a tuple containing the amount that should be added to the start
    and removed from the end of the axis.

    """
    start_entropy = utils.image_entropy(start_slice)
    end_entropy = utils.image_entropy(end_slice)
    if end_entropy and abs(start_entropy / end_entropy - 1) < 0.01:
        # Less than 1% difference, remove from both sides.
        if difference >= slice * 2:
            return slice, slice
        half_slice = slice // 2
        return half_slice, slice - half_slice
    if start_entropy > end_entropy:
        return 0, slice
    else:
        return slice, 0


def _points_table():
    """
    Iterable to map a 16 bit grayscale image to 8 bits.
    """
    for i in range(256):
        for j in itertools.repeat(i, 256):
            yield j


def colorspace(im, bw=False, replace_alpha=False, **kwargs):
    """
    Convert images to the correct color space.

    A passive option (i.e. always processed) of this method is that all images
    (unless grayscale) are converted to RGB colorspace.

    This processor should be listed before :func:`scale_and_crop` so palette is
    changed before the image is resized.

    bw
        Make the thumbnail grayscale (not really just black & white).

    replace_alpha
        Replace any transparency layer with a solid color. For example,
        ``replace_alpha='#fff'`` would replace the transparency layer with
        white.

    """
    if im.mode == 'I':
        # PIL (and pillow) have can't convert 16 bit grayscale images to lower
        # modes, so manually convert them to an 8 bit grayscale.
        im = im.point(list(_points_table()), 'L')

    is_transparent = utils.is_transparent(im)
    is_grayscale = im.mode in ('L', 'LA')
    new_mode = im.mode
    if is_grayscale or bw:
        new_mode = 'L'
    else:
        new_mode = 'RGB'

    if is_transparent:
        if replace_alpha:
            if im.mode != 'RGBA':
                im = im.convert('RGBA')
            base = Image.new('RGBA', im.size, replace_alpha)
            base.paste(im, mask=im)
            im = base
        else:
            new_mode = new_mode + 'A'

    if im.mode != new_mode:
        im = im.convert(new_mode)

    return im


def autocrop(im, autocrop=False, **kwargs):
    """
    Remove any unnecessary whitespace from the edges of the source image.

    This processor should be listed before :func:`scale_and_crop` so the
    whitespace is removed from the source image before it is resized.

    autocrop
        Activates the autocrop method for this image.

    """
    if autocrop:
        # If transparent, flatten.
        if utils.is_transparent(im):
            no_alpha = Image.new('L', im.size, (255))
            no_alpha.paste(im, mask=im.split()[-1])
        else:
            no_alpha = im.convert('L')
        # Convert to black and white image.
        bw = no_alpha.convert('L')
        # bw = bw.filter(ImageFilter.MedianFilter)
        # White background.
        bg = Image.new('L', im.size, 255)
        bbox = ImageChops.difference(bw, bg).getbbox()
        if bbox:
            im = im.crop(bbox)
    return im


def scale_and_crop(im, size, crop=False, upscale=False, zoom=None, target=None,
                   **kwargs):
    """
    Handle scaling and cropping the source image.

    Images can be scaled / cropped against a single dimension by using zero
    as the placeholder in the size. For example, ``size=(100, 0)`` will cause
    the image to be resized to 100 pixels wide, keeping the aspect ratio of
    the source image.

    crop
        Crop the source image height or width to exactly match the requested
        thumbnail size (the default is to proportionally resize the source
        image to fit within the requested thumbnail size).

        By default, the image is centered before being cropped. To crop from
        the edges, pass a comma separated string containing the ``x`` and ``y``
        percentage offsets (negative values go from the right/bottom). Some
        examples follow:

        * ``crop="0,0"`` will crop from the left and top edges.

        * ``crop="-10,-0"`` will crop from the right edge (with a 10% offset)
          and the bottom edge.

        * ``crop=",0"`` will keep the default behavior for the x axis
          (horizontally centering the image) and crop from the top edge.

        The image can also be "smart cropped" by using ``crop="smart"``. The
        image is incrementally cropped down to the requested size by removing
        slices from edges with the least entropy.

        Finally, you can use ``crop="scale"`` to simply scale the image so that
        at least one dimension fits within the size dimensions given (you may
        want to use the upscale option too).

    upscale
        Allow upscaling of the source image during scaling.

    zoom
        A percentage to zoom in on the scaled image. For example, a zoom of
        ``40`` will clip 20% off each side of the source image before
        thumbnailing.

    target
        Set the focal point as a percentage for the image if it needs to be
        cropped (defaults to ``(50, 50)``).

        For example, ``target="10,20"`` will set the focal point as 10% and 20%
        from the left and top of the image, respectively. If the image needs to
        be cropped, it will trim off the right and bottom edges until the focal
        point is centered.

        Can either be set as a two-item tuple such as ``(20, 30)`` or a comma
        separated string such as ``"20,10"``.

        A null value such as ``(20, None)`` or ``",60"`` will default to 50%.
    """
    source_x, source_y = [float(v) for v in im.size]
    target_x, target_y = [int(v) for v in size]