core.log("Script to modify FITS header in FITS and XISF files");

function checkFITS(key)
{
    const noEditableKey = ["SIMPLE", "BITPIX", "NAXIS", "NAXIS1", "NAXIS2", "NAXIS3", "EXTEND", "BZERO", "BSCALE"];
    return noEditableKey.indexOf(key) < 0;
}

if(files.length == 0)
{
    core.log("No input files");
    throw "";
}

let action = core.getItem(["UPDATE", "UPDATE_ADD", "ADD", "REMOVE"], "Do you want update, add or remove record?");

let modify = new FITSRecordModify();

let proceed = false;

if(action == "UPDATE")
{
    let keywords = files[0].fitsKeywords().filter(checkFITS);
    let keyword = core.getItem(keywords, "Select keyword to update");
    let value = files[0].fitsValue(keyword);
    if(isNaN(value))
        value = core.getString("Enter new value", value);
    else
        value = core.getFloat("Enter new value", value);

    if(keyword && value)
    {
        proceed = true;
        modify.updateKeyword(keyword, value);
    }
}
else if(action == "UPDATE_ADD")
{
    let keyword = core.getString("Enter keyword to update");
    let value = core.getString("Enter new value");
    if(keyword && value)
    {
        proceed = true;
        keyword = keyword.toUpperCase();
        modify.updateKeyword(keyword, value);
    }
}
else if(action == "ADD")
{
    let keyword = core.getString("Enter keyword to add");
    let value = core.getString("Enter new value");
    if(keyword && value)
    {
        proceed = true;
        keyword = keyword.toUpperCase();
        modify.addKeyword(keyword, value);
    }
}
else if(action == "REMOVE")
{
    let keywords = files[0].fitsKeywords().filter(checkFITS);
    let keyword = core.getItem(keywords, "Select keyword to remove");
    if(keyword)
    {
        proceed = true;
        modify.removeKeyword(keyword);
    }
}

if(proceed)
{
    for(file of files)
    {
        if(file.suffix() == "fits" || file.suffix() == "fit" || file.suffix() == "xisf")
        {
            core.log("Modifing " + file.fileName());
            file.modifyFITSRecords(modify);
        }
    }
}
else
{
    core.log("Canceled");
}

