import os
import hashlib
from calculate.utils.files import Process, write_file, read_file

class ImageMagickError(Exception):
    pass

class ImageMagick:
    def __init__(self, prefix='/'):
        self.prefix = prefix
        self.init_commands(prefix)
        self.default_opts = []

    @property
    def available(self):
        return self.convert_cmd and self.identify_cmd

    @property
    def chroot(self):
        return self.prefix != '/'

    def init_commands(self, prefix):
        self.convert_cmd = "/usr/bin/convert"
        self.identify_cmd = "/usr/bin/identify"
        self.chroot_cmd = "/bin/chroot"
        self.bash_cmd = "/bin/bash"
        if not os.path.exists(os.path.join(prefix, self.convert_cmd[1:])):
            self.convert_cmd = None
        if not os.path.exists(os.path.join(prefix, self.identify_cmd[1:])):
            self.identify_cmd = None

    def trim_prefix_path(self, filename):
        retpath = "/%s" % os.path.relpath(filename, self.prefix)
        if retpath.startswith("/.."):
            return None
        return retpath

    def get_image_resolution(self, source):
        if self.chroot:
            identify = Process(self.chroot_cmd, self.prefix,
                               self.bash_cmd, "-c",
                               " ".join([self.identify_cmd,
                                        "-format '%w %h'", source]))
        else:
            identify = Process(self.identify_cmd, "-format", "%w %h", source)
        if identify.success():
            swidth, _sep, sheight = identify.read().strip().partition(" ")
            if swidth.isdigit() and sheight.isdigit():
                return int(swidth), int(sheight)
        return None

    def convert(self, source, target, *opts):
        command = [self.convert_cmd, "-quality", "95",
                   source]
        command.extend(self.default_opts)
        command.extend(opts)
        command.append(target)
        if self.chroot:
            convert = Process(self.chroot_cmd, self.prefix,
                              self.bash_cmd, "-c",
                              " ".join(command))
        else:
            convert = Process(*command)
        if convert.success():
            return True
        else:
            print(convert.read_error())
        return False

    def convert_resize_crop_center(self, source, target, height, width):
        #if ((width == self.source_width and height == self.source_height) and
        #        (source.rpartition('.')[2] == target.rpartition('.')[2])):
        #    with write_file(target) as sf:
        #        sf.write(read_file(source))
        #    return True
        res = "%dx%d" % (width, height)

        return self.convert(source, target, "-quality", "95",
            "-resize", "%s^" % res,
            "-strip", "-gravity", "center",
            "-crop", "%s+0+0" % res)

    def convert_resize_gfxboot(self, source, target, height, width):
        res = "%dx%d" % (width, height)

        return self.convert(source, target, "-quality", "95",
            "-resize", "%s^" % res,
            "-strip", "-gravity", "center",
            "-crop", "%s+0+0" % res, 
            "-sampling-factor", "2x2",
            "-interlace", "none",
            "-set", "units", "PixelsPerSecond")
