
import java.util.logging.Logger;
import java.util.logging.Level;
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;



// Engine --> Servlet
//
// 1. exception (decoded inside 2 3)
//
// 2. response from cutout:   struct cutout_res_s  --> CutResult
//    .filesize
//    .filename
//    .nullval_count : {fill_ratio null_count total_count}
//
// NOTE: MCutout moved to -> dacc/JdlMCutout.java
// 3. response from mcutout:  struct mcutout_res_s --> MCutResult
//    .filesize
//    .tgz_filename
//    .cut_resp_s[] : {cut_param_s content_type content}
//
//    cut_param_s : {pubdid, coordonates, bool-countNullVals, filename, hdunum, cards[]}



public class JsonDecoder
{
 static final Logger LOGGER = Logger.getLogger(JsonDecoder.class.getName());

   public static CutResult responseFromCutoutJson(String response)
   {
      CutResult cut = new CutResult();

      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");

            JSONObject jnvc  = (JSONObject)jsonObject.get("nullvals_count");
            double fillRatio = (double) jnvc.get("fillratio");
            long null_count  = (long) jnvc.get("nullcount");
            long total_count = (long) jnvc.get("totalcount");

            cut.fileSize = fileSize;
            cut.fileName = fileName;
            cut.nullValueCount.percent    = fillRatio;
            cut.nullValueCount.nullCount  = null_count;
            cut.nullValueCount.totalCount = total_count;
         }
      }
      catch  (ParseException e)
      {
         LOGGER.severe(e.getMessage());
         e.printStackTrace();
         throw new IllegalStateException("Internal system error.");
      }

      return cut;
   }
}

