
import java.util.logging.Logger;

import java.util.Iterator;
import java.util.ArrayList;
/* '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
{
   static final Logger LOGGER = Logger.getLogger(JdlMCutout.class.getName());


   /* 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;

            Resolver rsl = new ResolverFromId(null);//settings.dbConn, subsurveys);
                                                //ResolverByObsCore rsl = new ResolverByObsCore(settings.dbConn, subsurveys);
            rsl.resolve(publisherDid);

            extraCards = null;// 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);
      obj.put("cuts", arrCuts);

      return obj.toJSONString();
   }




   public static MCutResult responseFromMCutoutJson(String response)
   {   

      MCutResult cuts = new MCutResult();
      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");

            LOGGER.finest("jsonArray.size  [responses]: " + jsonArray.size());
            //MCutResult.Cut[] cutResArr = new MCutResult.Cut[jsonArray.size()];
            //LOGGER.finest("cutResArr.length[responses]: " + cutResArr.length);

            ArrayList<MCutResult.Cut> cutResList = new ArrayList<MCutResult.Cut>();

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

               MCutResult mc = new MCutResult();
               MCutResult.Cut cut = mc.new Cut();

               //cut.inputs  = null;//(Inputs)jObj.get("input");
               String ctype = (String)jObj.get("type");
               if(ctype.equals("FILENAME"))
                  cut.contentType = MCutResult.Cut.ContentType.FILENAME;
               else if(ctype.equals("BAD_REQUEST"))
                  cut.contentType = MCutResult.Cut.ContentType.BAD_REQUEST;
               else if(ctype.equals("SERVICE_ERROR"))
                  cut.contentType = MCutResult.Cut.ContentType.SERVICE_ERROR;

               cut.content = (String)jObj.get("content");
               cut.index = i;// FIXME should come from inputs ?
               cutResList.add(cut);
               i++;
            }

            cuts.fileSize = fileSize;
            cuts.fileName = fileName;
            cuts.cutResArr = cutResList.toArray(new MCutResult.Cut[0]);//cutResArr;
            LOGGER.finest("cuts.cutResArr.length[responses]: " + cuts.cutResArr.length);
         }
      }
      catch  (ParseException e)
      {
         e.printStackTrace();
         throw new IllegalStateException("Internal system error.");
      }
      return cuts;
   }





   public static String[] pubdidsFromReqJson(String reqJsonString)
   {
      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("id");
            i++;
         }
      }
      catch  (Exception e)
      { // FIXME ParseException and others
         e.printStackTrace();
      }
      return pubdids;
   }




}

