"""
    Copyright (C) 2023  Michael Ablassmeier <abi@grinser.de>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
 """
import os
import builtins
import json
import pprint
import nbdkit

API_VERSION = 2

blockMap = None
blockMapFile = None
image = None
debug = "0"


def config(key, value):
    """Read parameter values, needs to use open function via
    builtins as the python plugin itself defines it again"""
    global blockMap
    global blockMapFile
    global image
    global debug
    if key == "blockmap":
        blockMapFile = value
        with builtins.open(blockMapFile, "rb") as fh:
            blockMap = json.loads(fh.read())
        return
    if key == "disk":
        image = value
        return
    if key == "debug":
        debug = value
        return

    raise RuntimeError(f"Unsupported parameter: {key}")


def log(msg):
    global debug
    if debug == "1":
        nbdkit.debug(msg)


def config_complete():
    """Check if we have all required parameters"""
    global image
    global blockMap
    global blockMapFile
    if image is None or blockMap is None:
        raise RuntimeError(
            "Missing parameter: path to blockmap and disk files required."
        )

    if not os.path.exists(image):
        raise RuntimeError(f"Specified image file: [{image}] does not exist.")
    if not os.path.exists(blockMapFile):
        raise RuntimeError(f"Specified blockmap file: [{blockMapFile}] does not exit.")

    pprint.pprint(blockMap)


def thread_model():
    return nbdkit.THREAD_MODEL_PARALLEL


def open(readonly):
    """Open backup files and return FD for each"""
    fd = os.open(image, os.O_RDONLY)
    log(f"File descriptors: {fd}")
    return fd


def close(param):
    return 1


def get_size(h):
    """Loop through the metadata and calculate the complete
    virtual disk size"""
    global blockMap
    size = 0
    for m in blockMap:
        # use only size from full backup image
        if m["file"] == image:
            size += m["length"]
    log(f"DISK SIZE: {size}")
    return size


def pread(h, buf, offset, flags):
    """Return the right data during read operation.

    Function uses the generated block map to check where
    in the stream format the required block offset is to
    be found and maps it accordingly and returns requested
    data.

    There might be situations where this goes really wrong
    and usually this results in an non-readable disk image.
    By using the blockfilter plugin, it "should" work most
    of the time, because the requested block size does
    not span amongst multiple frames within the sparse
    backup format.. as it should match the physical
    sector size .. hopefully
    """
    global blockMap

    log(f"Handle: {h}")

    # get block where offset sort of matches
    data = bytearray()
    blockListFull = list(
        filter(
            lambda x: x["originalOffset"] <= offset and x["inc"] is not True, blockMap
        )
    )
    log("-------------------------------------------")
    log(f"matching blocklist from full backup: {blockListFull}")
    log("-------------------------------------------")
    if len(blockListFull) == 1:
        log("using first block from blocklist")
        block = blockListFull[0]
    else:
        log("Using block from full backup")
        block = blockListFull[-1]

    log(f"Processing block: {block}")

    fileOffset = block["offset"] - block["originalOffset"] + offset

    dataFile = block["file"]

    dataRange = fileOffset + len(buf)
    blockRange = fileOffset + block["length"]
    isData = block["data"]
    log(f"READ FROM: {dataFile}")
    log(f"READ AT: {fileOffset}")
    log(f"READ: {len(buf)}")
    log(f"DATA-RANGE: {dataRange}")
    log(f"BLOCK-RANGE: {blockRange}")

    if dataRange < blockRange or dataRange == blockRange:
        if isData is False:
            log("handle zero")
            data += b"\0" * len(buf)
        else:
            log("can read everything")
            data += os.pread(h, len(buf), fileOffset)
            log(f"received: {len(data)}")
    else:
        raise RuntimeError("Unexpected block range size.")

    if len(data) != len(buf):
        raise RuntimeError("Unexpected short read from file.")

    buf[:] = data
