package com.dbs.dbsec.httpTask;

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

import com.dbs.dbsec.util.ConsentConfig;

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;
import java.util.Map;
import java.util.concurrent.ExecutionException;

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

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

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

    try {
      Url = new URL(url);  // URL화 한다.
      HttpURLConnection conn = (HttpURLConnection) Url.openConnection(); // URL을 연결한 객체 생성.
      conn.setRequestMethod("POST"); // POST방식 통신
      conn.setDoOutput(true);       // 쓰기모드 지정
      conn.setDoInput(true);        // 읽기모드 지정
      conn.setUseCaches(false);     // 캐싱데이터를 받을지 안받을지
      conn.setDefaultUseCaches(false); // 캐싱데이터 디폴트 값 설정
      conn.setConnectTimeout(ConsentConfig.CONNECT_TIMEOUT);

      OutputStream os = conn.getOutputStream(); // 서버로 보내기 위한 출력 스트림
      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); // UTF-8로 전송
      bw.write(getPostString(hash)); // 매개변수 전송
      bw.flush();
      bw.close();
      os.close();

      InputStream is = conn.getInputStream();   //데이타를 받기위 구멍을 열어준다
      StringBuilder builder = new StringBuilder();   //문자열을 담기 위한 객체
      BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));  //문자열 셋 세팅

      String line;
      while ((line = reader.readLine()) != null) {
        builder.append(line + "\n");
      }

      result = builder.toString();

      conn.disconnect();
    } catch (ProtocolException e) {
//      result = "[{\"code\":\"99\", \"errorMsg\":\"ProtocolException\"}]";
      result = "[{\"code\":\"99\", \"errorMsg\":\"" + e + "\"}]";
      e.printStackTrace();
    } catch (MalformedURLException e) {
//      result = "[{\"code\":\"99\", \"errorMsg\":\"MalformedURLException\"}]";
      result = "[{\"code\":\"99\", \"errorMsg\":\"" + e + "\"}]";
      e.printStackTrace();
    } catch (IOException e) {
//      result = "[{\"code\":\"99\", \"errorMsg\":\"IOException\"}]";
      result = "[{\"code\":\"99\", \"errorMsg\":\"" + e + "\"}]";
      e.printStackTrace();
    } catch (Exception e) {
      Log.e(TAG, "Exception");
      result = "[{\"code\":\"99\", \"errorMsg\":\"" + e + "\"}]";
      e.printStackTrace();
    }

    return result;
  }

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


  private String getPostString(HashMap<String, String> map) {

    StringBuilder result = new StringBuilder();
    boolean first = true; // 첫 번째 매개변수 여부

    for (Map.Entry<String, String> entry : map.entrySet()) {
      if (first)
        first = false;
      else // 첫 번째 매개변수가 아닌 경우엔 앞에 &를 붙임
        result.append("&");
      try { // UTF-8로 주소에 키와 값을 붙임
        result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
      } catch (UnsupportedEncodingException ue) {
        ue.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return result.toString();
  }
}