package com.dbs.mplus.knuh.httpTask;

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

import com.dbs.mplus.knuh.BuildConfig;
import com.dbs.mplus.knuh.util.ConsentConfig;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.HashMap;

public class HttpSoapConnection extends AsyncTask<Void, Void, SoapObject> {
  
  private static final String TAG = "HttpSoapConnection";
  private HashMap<String, String> mData;
  private String soapAction  = "";
  private String callMethod = "";
  
  public HttpSoapConnection(String soapAction, String callMethod, HashMap<String, String> mData) {
    this.soapAction  = soapAction;
    this.callMethod = callMethod;
    this.mData       = mData;
  }
  
  @Override
  protected void onPreExecute() {
  }
  
  @Override
  protected SoapObject doInBackground(Void... voids) {
    
    SoapObject soapObject  = soapRequestParam(callMethod, mData);
    SoapObject soapResponse = null;

    try {
      
      SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
      soapEnvelope.bodyOut = soapObject;
      soapEnvelope.setOutputSoapObject(soapObject);
      soapEnvelope.dotNet = true;
      soapEnvelope.implicitTypes = false;

      Log.e(TAG, "soapAction -- > " + soapAction);
      Log.e(TAG, "callMmethod -- > " + callMethod);
      HttpTransportSE hts = new HttpTransportSE(soapAction, ConsentConfig.CONNECT_TIMEOUT);
      hts.call(soapAction + callMethod, soapEnvelope);

      if (soapEnvelope.getResponse() instanceof SoapObject) {
        soapResponse = (SoapObject) soapEnvelope.getResponse();
      } else {
        soapResponse = new SoapObject();
        soapResponse.addProperty(callMethod, soapEnvelope.getResponse());
      }

      if (soapResponse != null) {
        return soapResponse;
      } else {
//        errorObject.addProperty("ERROR", "ERROR");
      }
      
    } catch (IOException e) {
      e.printStackTrace();
      Log.e(TAG, "서버에서 요청을 처리할 수 없습니다 -- > " + callMethod);
    } catch (XmlPullParserException e) {
      e.printStackTrace();
    }
    
    return null;
  }
  
  @Override
  protected void onPostExecute(SoapObject o) {
//    super.onPostExecute(o);
  }
  
  private SoapObject soapRequestParam(String callMmethod, HashMap<String, String> hashMap) {
    SoapObject soapObject = new SoapObject(BuildConfig.NAME_SPACE, callMmethod);
    
    for (String key : hashMap.keySet()) {
      soapObject.addProperty(key, hashMap.get(key));
    }
    
    return soapObject;
  }
}
