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

#include "ppImage.h"

// calculate stats from headers and concepts
bool ppImageMetadataStats (pmConfig *config, const ppImageOptions *options) {

    bool mdok;              // Status of MD lookup
    
    if (!options->doStats) {
	return true;
    }

    psMaskType maskVal = options->satMask | options->badMask | options->maskValue;

    // Extract statistics from the last output fpa
    pmFPAfile *outImage  = psMetadataLookupPtr(&mdok, config->files, "PPIMAGE.OUTPUT");
    pmFPAfile *outPhotom = psMetadataLookupPtr(&mdok, config->files, "PSPHOT.OUTPUT");
    pmFPAfile *outAstrom = psMetadataLookupPtr(&mdok, config->files, "PSASTRO.OUTPUT");

    if (!outImage && !outPhotom && !outAstrom) {
	psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find any output file (PPIMAGE.OUTPUT, PSPHOT.OUTPUT, PSASTRO.OUTPUT).");
	return false;
    }

    // get the latest output product available
    pmFPAfile *output = outAstrom;
    if (!output) {
	output = outPhotom;
    }
    if (!output) {
	output = outImage;
    }

    // select or create the fpa-level analysis stats metadata for PPIMAGE.OUTPUT:
    psMetadata *stats = psMetadataLookupPtr (&mdok, outImage->fpa->analysis, "PPIMAGE.STATS");
    psMemIncrRefCounter (stats);
    if (!stats) {
	stats = psMetadataAlloc ();
	if (!psMetadataAdd (outImage->fpa->analysis, PS_LIST_TAIL, "PPIMAGE.STATS", PS_DATA_METADATA, "stats container", stats)) {
	    psError(PS_ERR_UNKNOWN, false, "Unable to push stats on fpa.analysis.");
	    psFree (stats);
	    return false;
	}
    }

    // extract stats for the complete fpa 
    pmFPAview *view = pmFPAviewAlloc(0);

    if (!ppStatsMetadata(stats, output->fpa, view, maskVal, config)) {
	psError(PS_ERR_UNEXPECTED_NULL, false, "Unable to generate stats for image.");
	psFree(view);
	psFree(stats);
	return false;
    }

    psFree(view);
    psFree(stats);
    return true;
}
