
import java.util.logging.Logger;



class ResolverFromId implements Resolver
{
   private static final Logger LOGGER = Logger.getLogger(ResolverFromId.class.getName());

   private Subsurvey[] subsurveys;

   private String   relPathname;
   private int      hdunum;
   private String   subsurveyId;

   public ResolverFromId(Subsurvey[] subsurveys)
   {
      this.subsurveys = subsurveys;
   }


   public String relPathname() {return this.relPathname;}
   public int    hdunum() {return this.hdunum;}
   public String obsCollection() { return this.subsurveyId; }

   public void resolve(String pubdid)
   {
      LOGGER.fine("trace " + pubdid);

      boolean isIvoid = pubdid.substring(0,6).equals("ivo://");

      if(isIvoid)
      {
         resolveIvoid(pubdid);

         // FIXME resolve subsurveyId by matching relPathname to subsurveys::storage-path & file-filter

         LOGGER.finer("relPathname : " + relPathname);
         LOGGER.finer("hdunum      : " + String.valueOf(hdunum));
         LOGGER.finer("subsurveyId : " + ((subsurveyId == null) ? "null" : this.subsurveyId) );
      }
      else
      {
         throw new IllegalArgumentException("IVOID expected: ID must start with 'ivo://' but received: " + pubdid);
      }
   }



   private void resolveIvoid(String pubdid)
   {
      LOGGER.fine("trace " + pubdid);

      int qmarkIx = pubdid.lastIndexOf("?");
      int dhashIx = pubdid.lastIndexOf("#");// returns -1 if hash not found

      boolean hash_not_found = (dhashIx < 0);

      if(hash_not_found)
      {
         relPathname = pubdid.substring(  qmarkIx + 1 );
         hdunum = 1;
      }
      else
      {
         relPathname = pubdid.substring(  qmarkIx + 1, dhashIx );

         if((dhashIx+1) == pubdid.length())
            throw new IllegalArgumentException(
                  "if ID's last hash must be followed by HDU extension number however: " + pubdid);
         else
            hdunum = 1 + Integer.parseInt( pubdid.substring( dhashIx + 1 ) );
      }
   }


}

