package leigh.astro.iraf;

import au.com.bytecode.opencsv.CSVReader;
import leigh.mecha.exec.VelocityTask;
import leigh.mecha.util.StringUtil;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import java.util.UUID;

/**
 * Starfind searches the input image for local density maxima with half-widths at half-maxima of
 * <code>hwhmpsf</code> and peak amplitudes greater than <code>~threshold</code> above the local
 * background, and stores the result in an array of {@link StarInfo} objects.
 *
 * @author Alex Leigh
 */
public class StarFindTask extends VelocityTask {
    private final UUID imageUUID;
    private final String workDir;
    private final File tmpFile = File.createTempFile("leigh-astro", "txt");
    private final Photometry photometry = new Photometry();

    public StarFindTask(UUID imageUUID, String workDir) throws IOException {
        super("/leigh/astro/iraf/starfind.vm");
        this.imageUUID = imageUUID;
        this.workDir = workDir;
    }

    @SuppressWarnings("unused")
    public UUID getImageUUID() {
        return imageUUID;
    }

    public Photometry getPhotometry() {
        return photometry;
    }


    @SuppressWarnings("unused")
    public String getWorkDir() {
        return workDir;
    }

    @SuppressWarnings("unused")
    public File getTmpFile() {
        return tmpFile;
    }

    @Override
    public String toString() {
        return "StarFindTask{" +
                "imageUUID=" + imageUUID +
                ", workDir='" + workDir + '\'' +
                ", tmpFile=" + tmpFile +
                ", photometry=" + photometry +
                "} " + super.toString();
    }

    @Override
    public void finished(String result) throws IOException {
        super.finished(result);
        Reader in = new FileReader(tmpFile);

        /*
         * # Columns
         * #     1: X      2: Y
         * #     3: Mag    4: Area
         * #     5: Hwhm   6: Roundness
         * #     7: Pa     8: Sharpness
         */

        try (CSVReader reader = new CSVReader(in, ' ')) {
            String[] record;
            while ((record = reader.readNext()) != null) {
                List<String> rec = StringUtil.makeList(record);
                if (rec.size() == 0) continue;
                if (rec.get(0).equals("#")) continue;
                photometry.addStar(new StarInfo(rec));
            }
        }
    }
}
