package leigh.astro.app;

import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;
import nom.tam.fits.Fits;
import nom.tam.fits.FitsException;
import nom.tam.fits.Header;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

/**
 * Utility application designed to fix the header information in FITS files which were created prior to
 * Standardization. This would be FITS files with the old filter names, and with improper instrument data.
 *
 * @author Alex Leigh
 */
public class FixupApp {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(FixupApp.class);
    public static String KEY_FILTER = "FILTER";


    public static void main(String[] args) throws IOException {
        logger.info("Version: {}", FixupApp.class.getPackage().getImplementationVersion());
        Files.walkFileTree(Path.of("/Volumes/cal326/adb"), new SimpleFileVisitor<>() {
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                if (file.toString().endsWith(".fits") || file.toString().endsWith(".fit")) {
                    try {
                        Fits f = new Fits(file.toAbsolutePath().toString());
                        Header header = f.getHDU(0).getHeader();

                        String filter = header.getStringValue(KEY_FILTER);

                        switch (filter) {
                            case "H_Alpha":
                                header.addValue(KEY_FILTER, "HA_AD_3NM", "Filter");
                                break;
                            case "SII":
                                header.addValue(KEY_FILTER, "SII_AD_3NM", "Filter");
                                break;
                            case "OIII":
                                header.addValue(KEY_FILTER, "OIII_AD_3NM", "Filter");
                                break;
                            case "Red":
                                header.addValue(KEY_FILTER, "RED_AD_GEN2E", "Filter");
                                break;
                            case "Green":
                                header.addValue(KEY_FILTER, "GREEN_AD_GEN2E", "Filter");
                                break;
                            case "Blue":
                                header.addValue(KEY_FILTER, "BLUE_AD_GEN2E", "Filter");
                                break;
                        }

                        logger.debug("Read. [fn: {}] [filter: {}]", file, filter);
                    } catch (FitsException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        });
    }
}
