#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <string.h>
#include <pslib.h>
#include <psmodules.h>
#include <psphot.h>

#include "ppStack.h"

bool ppStackCamera(pmConfig *config)
{
    psMetadata *inputs = psMetadataLookupMetadata(NULL, config->arguments, "INPUTS"); // The inputs info
    psMetadataIterator *iter = psMetadataIteratorAlloc(inputs, PS_LIST_HEAD, NULL); // Iterator
    psMetadataItem *item;               // Item from iteration
    int i = 0;                          // Counter
    while ((item = psMetadataGetAndIncrement(iter))) {
        if (item->type != PS_DATA_METADATA) {
            psError(PS_ERR_BAD_PARAMETER_TYPE, true,
                    "Component %s of the input metadata is not of type METADATA", item->name);
            psFree(iter);
            return false;
        }

        psMetadata *input = item->data.md; // The input metadata of interest

        psString image = psMetadataLookupStr(NULL, input, "IMAGE"); // Name of image
        if (!image || strlen(image) == 0) {
            psError(PS_ERR_BAD_PARAMETER_VALUE, true, "Component %s lacks IMAGE of type STR", item->name);
            psFree(iter);
            return false;
        }

        bool mdok;
        psString mask = psMetadataLookupStr(&mdok, input, "MASK"); // Name of mask

        float seeing = psMetadataLookupF32(NULL, input, "SEEING"); // Seeing FWHM
        if (isnan(seeing)) {
            psError(PS_ERR_BAD_PARAMETER_VALUE, true, "Component %s lacks SEEING of type F32", item->name);
            psFree(iter);
            return false;
        }

        float weight = psMetadataLookupF32(NULL, input, "WEIGHT"); // Relative weight
        if (isnan(weight)) {
            psError(PS_ERR_BAD_PARAMETER_VALUE, true, "Component %s lacks WEIGHT of type F32", item->name);
            psFree(iter);
            return false;
        }

        float scale = psMetadataLookupF32(NULL, input, "SCALE"); // Relative scale
        if (isnan(scale)) {
            psError(PS_ERR_BAD_PARAMETER_VALUE, true, "Component %s lacks SCALE of type F32", item->name);
            psFree(iter);
            return false;
        }

        // Add the image file
        psArray *imageFiles = psArrayAlloc(1); // Array of filenames for this FPA
        imageFiles->data[0] = psMemIncrRefCounter(image);
        psMetadataAddArray(config->arguments, PS_LIST_TAIL, "IMAGE.FILENAMES", PS_META_REPLACE,
                           "Filenames of image files", imageFiles);
        psFree(imageFiles);

        bool found = false;             // Found the file?
        pmFPAfile *imageFile = pmFPAfileDefineFromArgs(&found, config, "PPSTACK.INPUT", "IMAGE.FILENAMES");
        if (!imageFile || !found) {
            psError(PS_ERR_UNKNOWN, false, "Unable to define file from image %d (%s)", i, image);
            return false;
        }
        if (imageFile->type != PM_FPA_FILE_IMAGE) {
            psError(PS_ERR_IO, true, "PPSTACK.INPUT is not of type IMAGE");
            return false;
        }

        // Optionally add the mask file
        if (mask && strlen(mask) > 0) {
            psArray *maskFiles = psArrayAlloc(1); // Array of filenames for this FPA
            maskFiles->data[0] = psMemIncrRefCounter(mask);
            psMetadataAddArray(config->arguments, PS_LIST_TAIL, "MASK.FILENAMES", PS_META_REPLACE,
                               "Filenames of mask files", maskFiles);
            psFree(maskFiles);

            bool status;
            pmFPAfile *maskFile = pmFPAfileBindFromArgs(&status, imageFile, config, "PPSTACK.INPUT.MASK", "MASK.FILENAMES");
            if (!status) {
                psError(PS_ERR_UNKNOWN, false, "Unable to define file from mask %d (%s)", i, mask);
                return false;
            }
            if (maskFile->type != PM_FPA_FILE_MASK) {
                psError(PS_ERR_IO, true, "PPSTACK.INPUT.MASK is not of type MASK");
                return false;
            }
        }

        psMetadataAddF32(imageFile->fpa->analysis, PS_LIST_TAIL, "PPSTACK.SEEING", 0,
                         "Seeing for image", seeing);
        psMetadataAddF32(imageFile->fpa->analysis, PS_LIST_TAIL, "PPSTACK.WEIGHT", 0,
                         "Relative weight for image", weight);
        psMetadataAddF32(imageFile->fpa->analysis, PS_LIST_TAIL, "PPSTACK.SCALE", 0,
                         "Relative scale for image", scale);

        i++;
    }
    psFree(iter);
    psMetadataRemoveKey(config->arguments, "IMAGE.FILENAMES");
    if (psMetadataLookup(config->arguments, "MASK.FILENAMES")) {
        psMetadataRemoveKey(config->arguments, "MASK.FILENAMES");
    }

    psMetadataAddS32(config->arguments, PS_LIST_TAIL, "INPUTS.NUM", 0, "Number of input files", i);

    // Output image
    pmFPA *fpa = pmFPAConstruct(config->camera); // FPA to contain the output
    if (!fpa) {
        psError(PS_ERR_UNEXPECTED_NULL, false, "Unable to construct an FPA from camera configuration.");
        return false;
    }
    pmFPAfile *output = pmFPAfileDefineOutput(config, fpa, "PPSTACK.OUTPUT");
    psFree(fpa);                        // Drop reference
    if (!output) {
        psError(PS_ERR_IO, false, _("Unable to generate output file from PPSTACK.OUTPUT"));
        return false;
    }
    if (output->type != PM_FPA_FILE_IMAGE) {
        psError(PS_ERR_IO, true, "PPSTACK.OUTPUT is not of type IMAGE");
        return false;
    }

    // Generate the correct structure
    pmFPALevel phuLevel = pmFPAPHULevel(output->format); // Level at which PHU goes
    pmFPAview *view = pmFPAviewAlloc(0);// View for current level
    if (phuLevel == PM_FPA_LEVEL_FPA) {
        if (!pmFPAAddSourceFromView(fpa, "Stack", view, output->format)) {
            psError(PS_ERR_UNKNOWN, false, "Unable to add PHU to FPA.");
            psFree(fpa);
            psFree(view);
            return NULL;
        }
    } else {
        pmChip *chip;                       // Chip from FPA
        while ((chip = pmFPAviewNextChip(view, fpa, 1))) {
            if (phuLevel == PM_FPA_LEVEL_CHIP) {
                if (!pmFPAAddSourceFromView(fpa, "Stack", view, output->format)) {
                    psError(PS_ERR_UNKNOWN, false, "Unable to add PHU to FPA.");
                    psFree(fpa);
                    psFree(view);
                    return NULL;
                }
            } else {
                pmCell *cell;                   // Cell from chip
                while ((cell = pmFPAviewNextCell(view, fpa, 1))) {
                    if (phuLevel == PM_FPA_LEVEL_CELL) {
                        if (!pmFPAAddSourceFromView(fpa, "Stack", view, output->format)) {
                            psError(PS_ERR_UNKNOWN, false, "Unable to add PHU to FPA.");
                            psFree(fpa);
                            psFree(view);
                            return NULL;
                        }
                    }
                }
            }
        }
    }
    psFree(view);

    // Output mask
    pmFPAfile *outMask = pmFPAfileDefineOutput(config, output->fpa, "PPSTACK.OUTPUT.MASK");
    if (!outMask) {
        psError(PS_ERR_IO, false, _("Unable to generate output file from PPSTACK.OUTPUT.MASK"));
        return false;
    }
    if (outMask->type != PM_FPA_FILE_MASK) {
        psError(PS_ERR_IO, true, "PPSTACK.OUTPUT.MASK is not of type MASK");
        return false;
    }

    return true;
}
