# Needed on case-insensitive filesystems
from __future__ import absolute_import
from scipy.misc import imsave
import numpy as np
from matplotlib.colors import ColorConverter
from matplotlib import pyplot as plt
import qrcode.image.base


class numpyImage(qrcode.image.base.BaseImage):
    """
    numpy-scipy image builder.
    """

    color_converter = ColorConverter()
    kind = "PNG"

    def __init__(self, *args, **kwargs):
        self.fill_color = (0, 0, 0)
        self.back_color = (1, 1, 1)
        self.alpha = False
        super(numpyImage, self).__init__(*args, **kwargs)

    def new_image(self, **kwargs):
        back_color = kwargs.get("back_color", "white")
        fill_color = kwargs.get("fill_color", "black")

        img = np.zeros((self.pixel_size, self.pixel_size, 4), dtype=np.float32)
        # Colors must become tuples for numpy solution:
        self.fill_color = self.color_converter.to_rgb(fill_color)
        self.alpha = back_color.lower() == "transparent"
        if not self.alpha:
            self.back_color = self.color_converter.to_rgb(back_color)
            img[:, :, 3] = 1

        img[:, :, :3] = np.array(self.back_color, dtype=np.float32)

        return img

    def drawrect(self, row, col):
        (x, y), (w, h) = self.pixel_box(row, col)
        # self._idr.rectangle(box, fill=self.fill_color)
        (r, g, b) = self.fill_color
        a = 1
        self._img[y:h+1, x:w+1] = np.array([r, g, b, a])

    def save(self, stream, format=None, **kwargs):
        imsave(stream, self._img, format=format)

    def show(self):
        fig = plt.figure()
        plt.imshow(self._img, interpolation="none")
        plt.show()
        return fig

    def __getattr__(self, name):
        return getattr(self._img, name)
