from pathlib import Path
import subprocess
import numpy as np


class Preprocessor:
    """
    use LibRaw's dcraw_emu to convert supported input file types to 16-bit linear images
    """

    extensions = [
        "NEF",  # Nikon
        "ARW",  # Sony
        "PEF",  # Pentax
        "IIQ",  # Phase One
        "MOS",  # Leaf
        "ORF",  # Olympus
        "RW2",  # Panasonic
        "RAF",  # Fujifilm -> bayer mode will probably break horribly
        "DNG",  # Pentax/Ricoh, maybe others
        "CR2",  # Canon
        "CR3"   # newer Canon
    ]

    def __init__(self, filename, verbose=False):
        self.filename = Path(filename)
        self.verbose = verbose

    def process(self):
        ext = str(self.filename.suffix).upper()[1:]

        if not ext in self.extensions:
            return False, str(self.filename)
        
        args = ["/usr/bin/dcraw_emu", "-w", "-4", "-T", "-q", "3", "-o", "0", 
                "-s", "0", "-H", "1", str(self.filename)]
        
        cp = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)

        if self.verbose and len(cp.stdout) > 0:
            print(cp.stdout)

        if cp.returncode == 0:
            return True, str(self.filename) + ".tiff"
        
        raise Exception("libraw failed " + cp.stdout)
