"""Read native-resolution fields from the Patrick Center's tiled grayscale OME-TIFF stacks."""
import ctypes as c
from ctypes.util import find_library
from pathlib import Path
import xml.etree.ElementTree as ET

from PIL import Image

lib = c.CDLL(find_library("tiff"))

def bind(name, result, *args):
    fn = getattr(lib, name)
    fn.argtypes = list(args)
    fn.restype = result
    return fn

handle = c.c_void_p
u32 = c.c_uint32
tiff_open = bind("TIFFOpen", handle, c.c_char_p, c.c_char_p)
tiff_close = bind("TIFFClose", None, handle)
get_field = bind("TIFFGetField", c.c_int, handle, u32)
set_dir = bind("TIFFSetDirectory", c.c_int, handle, u32)
set_subdir = bind("TIFFSetSubDirectory", c.c_int, handle, c.c_uint64)
tile_bytes = bind("TIFFTileSize", c.c_ssize_t, handle)
read_tile = bind("TIFFReadTile", c.c_ssize_t, handle, handle, u32, u32, u32, c.c_uint16)


class Stack:
    def __init__(self, path: Path):
        self.path = path

    def __enter__(self):
        self.file = tiff_open(bytes(self.path), b"r")
        if not self.file:
            raise OSError(f"Cannot open {self.path}")
        try:
            xml = self.tag(270, c.c_char_p)
            pix = ET.fromstring(xml).find(".//{*}Pixels")
            if (pix is None or pix.get("Type") != "uint8"
                    or pix.get("SizeC") != "1" or pix.get("SizeT") != "1"):
                raise ValueError("Expected one 8-bit grayscale OME stack")
            self.width, self.height, self.depth = (int(pix.attrib["Size"+a]) for a in "XYZ")
            if any(pix.get("PhysicalSize"+a+"Unit") != "µm" for a in "XY"):
                raise ValueError("Expected micrometre calibration")
            self.sx, self.sy = (float(pix.attrib["PhysicalSize"+a]) for a in "XY")
            mappings = pix.findall("{*}TiffData")
            if len(mappings) != 1 or int(mappings[0].get("IFD", 0)) != 0 or int(mappings[0].get("PlaneCount", 1)) != self.depth:
                raise ValueError("Expected consecutive Z directories starting at zero")
            self.plane(self.depth - 1)
            # Reduced views are stored after the primary planes in these files.
            # Probe the last level and its last tile to catch copies with missing tails.
            count, offsets = c.c_uint16(), c.POINTER(c.c_uint64)()
            if get_field(self.file, 330, c.byref(count), c.byref(offsets)) and count.value:
                if not set_subdir(self.file, offsets[count.value-1]):
                    raise OSError("Unreadable final pyramid directory")
            w, h = self.tag(256, u32), self.tag(257, u32)
            self.read_one(w-1, h-1)
            self.plane(0)
            return self
        except BaseException:
            tiff_close(self.file)
            raise

    def __exit__(self, *args):
        tiff_close(self.file)

    def tag(self, number, dtype):
        val = dtype()
        if not get_field(self.file, number, c.byref(val)):
            raise ValueError(f"Missing TIFF tag {number}")
        return val.value

    def plane(self, z):
        if not set_dir(self.file, z):
            raise OSError(f"Cannot read plane {z}")
        self.tw, self.th = self.tag(322, u32), self.tag(323, u32)
        if ((self.tag(256, u32), self.tag(257, u32)) != (self.width, self.height)
                or self.tag(277, c.c_uint16) != 1 or self.tag(258, c.c_uint16) != 8):
            raise ValueError("Inconsistent full-resolution plane")

    def read_one(self, x, y):
        n = tile_bytes(self.file)
        if not 0 < n <= 16 * 1024**2:
            raise ValueError("Unsupported tile size")
        buf = c.create_string_buffer(n)
        if read_tile(self.file, buf, x, y, 0, 0) != n:
            raise OSError(f"Incomplete tile at {x}, {y}")
        return buf.raw

    def field(self, z, x, y, side):
        self.plane(z)
        out = Image.new("L", (side, side))
        for yy in range(y // self.th * self.th, y + side, self.th):
            for xx in range(x // self.tw * self.tw, x + side, self.tw):
                raw = self.read_one(xx, yy)
                tile = Image.frombytes("L", (self.tw, self.th), raw)
                out.paste(tile, (xx-x, yy-y))
        return out
