
import java.util.Iterator;
/* 'JSON-Simple' library */
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;


public class JdlMCutout
{



   /* used in mcutout to resolve pubdids to pathanme+hdunum */
   public static String resolveAndUpdateJsonRequest(String reqJsonString, Settings settings, Subsurvey[] subsurveys)
   {
      String str = new String();

      JSONParser parser = new JSONParser();
      try
      {
         JSONArray a = (JSONArray) parser.parse(reqJsonString);

         for (Object o : a)
         {
            JSONObject cutParams = (JSONObject) o;

            String publisherDid = (String) cutParams.get("pubdid");

            /* resolve pubdid -> pathname hdunum extraCards */

            FitsCard[] extraCards = null;

            ResolverByObsCore rsl = new ResolverByObsCore(settings.dbConn, subsurveys);
            rsl.resolve(publisherDid);

            extraCards = Subsurvey.subsurveysFindCards(subsurveys, rsl.obsCollection());//subsurveyId);

            /* add resolved info to json */

            cutParams.put("filename",rsl.relPathname());
            cutParams.put("hdunum",rsl.hdunum());

            if(extraCards != null)
            {
               if(extraCards.length > 0)
               {
                  JSONArray jcards = new JSONArray();
                  for(FitsCard card : extraCards)
                  {
                     JSONObject jcard = new JSONObject();
                     jcard.put("key", card.key);
                     jcard.put("value", card.value);
                     jcard.put("comment", card.comment);
                     jcards.add(jcard);
                  }
                  cutParams.put("extra_cards", jcards);
               }
            }
         }

         str = a.toString();
      }
      catch(ParseException e)
      {
         e.printStackTrace();
      }

      return str;
   }



   @SuppressWarnings("unchecked")
   public static String mcutoutToJson(String reqJsonString)
   // FIXME this should do: throws ParsingError
   {
      JSONArray arrCuts;
      JSONParser parserCuts = new JSONParser();
      try
      {
         arrCuts = (JSONArray) parserCuts.parse(reqJsonString);
      }
      catch(ParseException pe)
      {
         System.out.println("mcutout json from HTTP-body incorrect");
         return "";
      }

      JSONObject objParameters = new JSONObject();
      objParameters.put("cuts", arrCuts);

      JSONObject obj = new JSONObject();
      obj.put("service",  "MCUTOUT");
      obj.put("parameters",  objParameters);

      return obj.toJSONString();
   }




   public static DataLink responseFromMCutoutJson(String response)
      // throws ParseException
   {   
      DataLink dlk = new DataLink();

      try {
         JSONParser parser = new JSONParser();
         Object jsonObj = parser.parse(response);
         JSONObject jsonObject  = (JSONObject) jsonObj;

         JSONObject jexcept = (JSONObject) jsonObject.get("exception");
         if(jexcept != null)
         {
            String type = (String)jexcept.get("type");
            String msg  = (String)jexcept.get("msg");
            if(type.equals("INVALID_PARAM"))
            {
               throw new IllegalArgumentException(msg);
            }
            else if(type.equals("SYSTEM_ERROR"))
            {
               throw new IllegalStateException("Internal system error.");
            }
         }
         else
         {
            long fileSize = (long) jsonObject.get("filesize");
            String fileName = (String) jsonObject.get("filename");

            JSONArray jsonArray = (JSONArray)jsonObject.get("responses");

            MCutResult[] mcutResArr = new MCutResult[jsonArray.size()];

            int i = 0;
            @SuppressWarnings("unchecked")
            Iterator<JSONObject> itr = jsonArray.iterator();
            while (itr.hasNext())
            {
               JSONObject jObj = itr.next();

               mcutResArr[i].inputs  = (Inputs)jObj.get("input");
               String ctype = (String)jObj.get("type");
               if(ctype.equals("FILENAME"))
                  mcutResArr[i].contentType = MCutResult.ContentType.FILENAME;
               else if(ctype.equals("BAD_REQUEST"))
                  mcutResArr[i].contentType = MCutResult.ContentType.BAD_REQUEST;
               else if(ctype.equals("SERVICE_ERROR"))
                  mcutResArr[i].contentType = MCutResult.ContentType.SERVICE_ERROR;
               mcutResArr[i].content = (String)jObj.get("content");
               i++;
            }

            dlk.contentLength = fileSize;
            dlk.accessUrl     = fileName;
            dlk.mcutResultArr = mcutResArr;
         }
      }   
      catch  (ParseException e)
      {   
         e.printStackTrace();
         throw new IllegalStateException("Internal system error.");
      }   
      return dlk;
   }





   public static String[] pubdidsFromReqJson(String reqJsonString)
      // throws ParseException
   {
      String[] pubdids = null;

      try
      {
         JSONParser parser = new JSONParser();
         JSONArray jsonArray = (JSONArray)parser.parse(reqJsonString);

         pubdids = new String[jsonArray.size()];

         int i = 0;
         @SuppressWarnings("unchecked")
         Iterator<JSONObject> itr = jsonArray.iterator();
         while (itr.hasNext())
         {
            JSONObject jObj = itr.next();
            pubdids[i] = (String)jObj.get("pubdid");
            i++;
         }
      }
      catch  (Exception e)
      { // FIXME ParseException and others
         e.printStackTrace();
      }
      return pubdids;
   }




}

