package org.mbari.vdm;

import java.net.MalformedURLException;
import java.net.URL;

import ucar.unidata.geoloc.LatLonPoint;
import ucar.unidata.geoloc.LatLonPointImpl;

public class VarsLine implements VdmLine {

    public boolean missingLat = false;
    final double lat;
    public boolean missingLon = false;
    final double lon;
    public boolean missingDepth = false;
    final float depth;
    final Long observationId_fk;
    final String conceptName;
    final String recordedDate;
    final String tapeTimeCode;
    final String videoArchiveName;
    final URL image;

    private static final String HEADER = "Latitude, Longitude, Depth, RecordedDate, "
        + "TapeTimeCode, ObservationID_FK, ConceptName, VideoArchiveName, Image";

    /**
     * expected order of parts array: Latitude, Longitude, Depth, RecordedDate,
     * TapeTimeCode, ObservationID_FK, ConceptName, VideoArchiveName, Image
     * 
     * @param parts
     * @throws MalformedURLException
     */
    public VarsLine(String[] parts) {
        if (parts == null || parts.length != 9) {
            throw new IllegalArgumentException("The parts array must be of length 9");
        }
        observationId_fk = Long.parseLong(parts[5]);
        conceptName = parts[6];
        if (parts[2] == null || parts[2].equals("null")) {
            depth = 0;
            missingDepth = true;
        } else {
            depth = Float.parseFloat(parts[2]);
        }
        if (parts[8] != null  && !parts[8].equals("null")) {
            try {
                image = new URL(parts[8]);
            } catch (MalformedURLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        } else {
            image = null;
        }
        if (parts[0] == null || parts[0].equals("null")) {
            lat = 0;
            missingLat = true;
        } else {
            lat = new Double(parts[0]);
        }
        if (parts[1] == null || parts[1].equals("null")) {
            lon = 0;
            missingLon = true;
        } else {
            lon = new Double(parts[1]);
        }
        recordedDate = parts[3];
        tapeTimeCode = parts[4];
        videoArchiveName = parts[7];
    }

    public LatLonPoint getPoint() {
        if(missingLat || missingLon){
            return null;
        }
        return new LatLonPointImpl(lat, lon);
    }
    
    public double getLat(){
        return lat;
    }
    
    public double getLon(){
        return lon;
    }
    public float getDepth(){
        return depth;
    }
    
    public String getHeader() {
        return HEADER;
    }

    public String toCsvString() {
        return lat + ", " + lon + ", " + depth + ", " + recordedDate + ", " +
            tapeTimeCode + ", " + observationId_fk + ", " + conceptName + ", " +
            videoArchiveName + ", " + image;
    }

}
