/*
 * Copyright (c) 2015. Ncomz. All Rights Reserved
 */

package com.ntels.kneet.v3.common.http;

import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;

import com.ntels.kneet.v3.common.exception.RequestUnsuccessfulException;
import com.ntels.kneet.v3.common.c_interface.OnDataSendToReslut;
import com.ntels.kneet.v3.common.c_interface.OnTaskExecutionFinished;
import com.ntels.kneet.v3.common.util.Dlog;
import com.ntels.kneet.v3.common.util.Util;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Implementation of the AIDL service. An {@link AsyncTask} is created per HTTP request and the response is returned from the {@link AsyncTask}. The parsing of
 * the response is managed by the {@link Response} class.
 * <p/>
 * <p/>
 * The intent this service listens to is as per HttpService.INTENT_NAME.
 * <p/>
 * The response is expected to return from AsyncTask within the time as specified in HttpService.DEFAULT_TIMEOUT. An exception will be thrown otherwise.
 *
 * @author s0pau
 */
public class HttpSendGeofence {

    private Util   util         = new Util();
    private static final String TAG             = HttpSendGeofence.class.getSimpleName();
    public static final  long   DEFAULT_TIMEOUT = 5000;
    private              String sInterface_Id   = "";
    private              String sSendType       = "GET";
    private              String sEnc            = "UTF-8";

    private String URL          = "http://maps.googleapis.com/maps/api/geocode/json?";
    private String HTTP_LATLNG  = "latlng";
    private String HTTP_ADDRESS = "address";

    private String HTTP_SENSOR   = "sensor";
    private String HTTP_LANGUAGE = "language";

    public final static int ENC_NOT = 10200;
    public final static int ENC_AES = 10201;

    private boolean bDialog = true;
    protected Context context;

    public HttpSendGeofence(Context context) {

        this.context = context;
    }

    public HttpSendGeofence(Context context, boolean bDialog) {

        this.context = context;
        this.bDialog = bDialog;
    }

    //	String	address	= String.format(Locale.ENGLISH, "http://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=true&language=" + Locale.getDefault().getCountry(),
    //							lat, lng);
    //	http://maps.googleapis.com/maps/api/geocode/json?sensor=false&language=ko&address=%EC%BD%94%EC%97%91%EC%8A%A4

    /**
     * *****************************************************************************************************
     * 규칙 상태 변경
     *
     * @return sReceiveData
     * ******************************************************************************************************
     */
    public void LatlngToAddress(String sHTTP_LATLNG, String sHTTP_SENSOR, String sHTTP_LANGUAGE) {

        String sUrl = URL;
        try {
            ArrayList<String> paramList = null;  // 파라메터 Value Buff
            ArrayList<HashMap<String, Object>> alPost = new ArrayList<HashMap<String, Object>>();
            addParameter(alPost,  HTTP_LATLNG, sHTTP_LATLNG);
            addParameter(alPost,  HTTP_SENSOR, sHTTP_SENSOR);
            addParameter(alPost,  HTTP_LANGUAGE, sHTTP_LANGUAGE);

            get(sUrl + convPostBody(alPost), "");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * *****************************************************************************************************
     * 규칙 상태 변경
     *
     * @return sReceiveData
     * ******************************************************************************************************
     */
    public void AddressToLatlng(String sHTTP_ADDRESS, String sHTTP_SENSOR, String sHTTP_LANGUAGE) {

        String sUrl = URL;
        try {
            ArrayList<String> paramList = null;  // 파라메터 Value Buff
            ArrayList<HashMap<String, Object>> alPost = new ArrayList<HashMap<String, Object>>();
            addParameter(alPost,  HTTP_ADDRESS, sHTTP_ADDRESS);
            addParameter(alPost,  HTTP_SENSOR, sHTTP_SENSOR);
            addParameter(alPost,  HTTP_LANGUAGE, sHTTP_LANGUAGE);

            get(sUrl + convPostBody(alPost), "");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String convPostBody(List<HashMap<String, Object>> params) throws Exception {
        StringBuilder result = new StringBuilder();
        boolean first = true;

        for ( int i = 0; i < params.size(); i++ ) {
            if ( first ) {
                first = false;
            } else {
                result.append("&");
            }

            for ( Map.Entry<String, Object> entry : params.get(i).entrySet() ) {
                result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                result.append("=");
                result.append(URLEncoder.encode(util.null2string(entry.getValue()), "UTF-8"));
            }
        }

        return result.toString();
    }

    void addParameter(List<HashMap<String, Object>> paramListPost, String parameterName, String parameterValue) {

        if ( parameterName == null ) {
            return;
        }
        HashMap<String, Object> hmTemp = new HashMap<String, Object>();
        if ( parameterValue == null ) {
            hmTemp.put(parameterName, "");
        } else {
            //            Dlog.v(parameterName + ": " + parameterValue);
            hmTemp.put(parameterName, parameterValue);
        }
        paramListPost.add(hmTemp);
    }
    /**
     * Helper method to make http get request with given params.
     *
     * @param uri
     * @param apiKey
     * @return response from the request made.
     */
    private void get(String uri, String apiKey) {
        CustomRequest customRequest = new CustomRequest(bDialog, CustomRequest.HTTP_METHOD_GET, uri, apiKey, "", CustomRequest.SEND_METHOD_GEOFENCE);
        executeRequest(customRequest);
    }

    private OnDataSendToReslut _task_resulted_event;
    private Dialog             dialog;

    private void executeRequest(CustomRequest customRequest) {
        //
        //		if (!bDialog) {
        //			if (dialog != null) {
        //				dialog.dismiss();
        //				dialog = null;
        //			}
        //		} else {
        //			if (dialog != null) {
        //				dialog.cancel();
        //				dialog = null;
        //			}
        //
        //			dialog = new Dialog(context, R.style.NTLES_Dialog1);
        //			dialog.addContentView(new ProgressBar(context, null, android.R.attr.progressBarStyleInverse), new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        //			dialog.show();
        //		}
        AsyncTask<CustomRequest, Integer, Response[]> task = null;
        try {
            task = new HttpTask(context);
            ((HttpTask) task).setOnTaskFinishedEvent(new OnTaskExecutionFinished() {

                @Override
                public void OnTaskFihishedEvent(Response[] result) {
                    // util.setShowToast(getApplicationContext(),
                    // "Phony thread finished: " + result,
                    // Toast.LENGTH_SHORT);
                    //					dataSendToActivity.resultResponse( result != null ? result[0] : null);
                    if ( dialog != null ) {
                        dialog.dismiss();
                        dialog = null;
                    }

                    if ( _task_resulted_event != null ) {
                        _task_resulted_event.resultResponse(result != null ? result[0] : null);
                    }
                }
            });
            task.execute(customRequest);
        } catch (RequestUnsuccessfulException e) {
            String msg1 = "Unable to execute request";
            Dlog.w(msg1, e);
            //			dataSendToActivity.resultResponse( ResponseHelper.writeException(msg1, e));
            _task_resulted_event.resultResponse(ResponseHelper.writeException(msg1, e));
        }
    }

    public void setOnDataSendToReslutEvent(OnDataSendToReslut _event) {
        if ( _event != null ) {
            this._task_resulted_event = _event;
        }
    }

}
