package com.dbs.mplus.fatima.httpTask;

import android.os.AsyncTask;
import android.util.Log;
import android.util.Xml;

import com.dbs.mplus.fatima.BuildConfig;
import com.dbs.mplus.fatima.util.Util;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

public class HttpCon extends AsyncTask<Void, Void, String> {
  private static final String TAG = "HttpCon";
  private String url = "";
  private String action = "";
  private HashMap<String, String> hash = new HashMap<>();

  public HttpCon(String _url, HashMap<String, String> _hash, String action){
    this.url = _url;
    this.hash = _hash;
    this.action = action;
  }

  @Override
  protected String doInBackground(Void... voids) {
    URL Url;
    String result = "";

    try {
      Log.e(TAG, "http reuqest " + action + " start -- > " + Util.logTime());
      Url = new URL(url);
      HttpURLConnection conn = (HttpURLConnection) Url.openConnection();
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
      conn.setRequestProperty("SOAPAction", "http://tempuri.org/" + action);
      conn.setDoInput(true);
      conn.setDoOutput(true);
      String xml = getPostXmlString(hash, action);

//      String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
//          "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
//          "  <soap:Body>\n" +
//          "    <CheckWebService xmlns=\"http://tempuri.org/\" />\n" +
//          "  </soap:Body>\n" +
//          "</soap:Envelope>";

//      String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
//          "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
//          "  <soap:Body>\n" +
//          "    <doLogin xmlns=\"http://tempuri.org/\">\n" +
//          "      <userid>105412</userid>\n" +
//          "      <pwd>47915507fe3d9bf4c2ea961c8b808d4a</pwd>\n" +
//          "    </doLogin>\n" +
//          "  </soap:Body>\n" +
//          "</soap:Envelope>";

//      String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
//          "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
//          "  <soap:Body>\n" +
//          "    <SaveTempData xmlns=\"http://tempuri.org/\">\n" +
//          "      <userId><![CDATA[" + hash.get("userId") + "]]></userId>\n" +
//          "      <patientCode><![CDATA[" + hash.get("patientCode") + "]]></patientCode>\n" +
//          "      <clnDeptCode><![CDATA[" + hash.get("clnDeptCode") + "]]></clnDeptCode>\n" +
//          "      <formRid><![CDATA[" + hash.get("formRid") + "]]></formRid>\n" +
//          "      <formCd><![CDATA[" + hash.get("formCd") + "]]></formCd>\n" +
//          "      <consentMstRid><![CDATA[" + hash.get("consentMstRid") + "]]></consentMstRid>\n" +
//          "      <rewriteConsentMstRid><![CDATA[" + hash.get("rewriteConsentMstRid") + "]]></rewriteConsentMstRid>\n" +
//          "      <formXml><![CDATA[" + hash.get("formXml") + "]]></formXml>\n" +
//          "      <dataXml><![CDATA[" + hash.get("dataXml") + "]]></dataXml>\n" +
//          "      <deviceType><![CDATA[" + hash.get("deviceType") + "]]></deviceType>\n" +
//          "      <deviceIdentNo><![CDATA[" + hash.get("deviceIdentNo") + "]]></deviceIdentNo>\n" +
//          "      <vistType><![CDATA[" + hash.get("vistType") + "]]></vistType>\n" +
//          "      <hosType><![CDATA[" + hash.get("hosType") + "]]></hosType>\n" +
//          "      <clnDate><![CDATA[" + hash.get("clnDate") + "]]></clnDate>\n" +
//          "      <ward><![CDATA[" + hash.get("ward") + "]]></ward>\n" +
//          "      <roomcd><![CDATA[" + hash.get("roomcd") + "]]></roomcd>\n" +
//          "      <orderNo><![CDATA[" + hash.get("orderNo") + "]]></orderNo>\n" +
//          "      <orderName><![CDATA[" + hash.get("orderName") + "]]></orderName>\n" +
//          "      <orderCd><![CDATA[" + hash.get("orderCd") + "]]></orderCd>\n" +
//          "      <ocrCode><![CDATA[" + hash.get("ocrCode") + "]]></ocrCode>\n" +
//          "      <cretno><![CDATA[" + hash.get("cretno") + "]]></cretno>\n" +
//          "      <createUserName><![CDATA[" + hash.get("createUserName") + "]]></createUserName>\n" +
//          "      <modifyUserName><![CDATA[" + hash.get("modifyUserName") + "]]></modifyUserName>\n" +
//          "      <mainDrId><![CDATA[" + hash.get("mainDrId") + "]]></mainDrId>\n" +
//          "    </SaveTempData>\n" +
//          "  </soap:Body>\n" +
//          "</soap:Envelope>";

//      Util.LOG(HttpCon.class, "xml -- > " + xml);

      conn.setRequestProperty("Content-Length", Integer.toString(xml.getBytes().length));

      OutputStream outputStream = conn.getOutputStream();
      BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
      bufferedWriter.write(xml);
      bufferedWriter.flush();
      bufferedWriter.close();
      outputStream.close();

      int status = conn.getResponseCode();
      Log.e(TAG, "status -- > " + status);

      InputStream inputStream = conn.getInputStream();
      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
      String line = "";
      while ((line = bufferedReader.readLine()) != null) {
        result += line;
      }

      bufferedReader.close();
      inputStream.close();

      conn.disconnect();

      Log.e(TAG, "http reuqest " + action + " end -- > " + Util.logTime());

//      Log.e(TAG, "result -- > " + result);
      JSONObject object = XML.toJSONObject(result);
      result = object.toString();

    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    }

    return result;
  }

  @Override
  protected void onPreExecute(){
    super.onPreExecute();
  }

  private String getPostXmlString(HashMap map, String action) {
    StringBuilder result = new StringBuilder();
    result.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    result.append("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
    result.append("<soap:Body>");

    result.append("<" + action + " xmlns=\"http://tempuri.org/\">");

    for (Object key : map.keySet()) {
      result.append("<" + key + ">");
      result.append("<![CDATA[");
      result.append(map.get(key).toString() == null ? "" : map.get(key).toString());
      result.append("]]>");
      result.append("</" + key + ">");
    }

    result.append("</" + action + ">");
    result.append("</soap:Body>");
    result.append("</soap:Envelope>");
    return result.toString();
  }

  private String getPostString(HashMap map) {
    StringBuilder result = new StringBuilder();
    boolean first = true; // 첫 번째 매개변수 여부

    for (Object key : map.keySet()) {
      if (first)
        first = false;
      else // 첫 번째 매개변수가 아닌 경우엔 앞에 &를 붙임
        result.append("&");

      try { // UTF-8로 주소에 키와 값을 붙임
        result.append(URLEncoder.encode(key.toString(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(map.get(key).toString(), "UTF-8"));
      } catch (UnsupportedEncodingException ue) {
        ue.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    Log.e(TAG, "result -- > " + result.toString());
    return result.toString();
  }
}