/*
 * 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.AppConfig;
import com.ntels.kneet.v3.common.Constants;
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 org.json.JSONException;
import org.json.JSONObject;

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 android.os.AsyncTask} is created per HTTP request and the response is returned from the {@link android.os.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 HttpSendSmart {

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

    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;
    private String sSmartUrl = "";

    public HttpSendSmart(Context context) {

        appConfig = (AppConfig) context.getApplicationContext();
        this.context = context;
        sSmartUrl = appConfig.getSmartUrl();
    }

    public HttpSendSmart(Context context, boolean bDialog) {

        appConfig = (AppConfig) context.getApplicationContext();
        this.context = context;
        this.bDialog = bDialog;
        sSmartUrl = appConfig.getSmartUrl();
    }

    public void contents(String sHTTP_DEVICES, String sHTTP_NODES, String authorization, String sContent_value) {

        String sUrl = sSmartUrl;
        try {
            ArrayList<String> paramList = null;  // 파라메터 Value Buff
            ArrayList<HashMap<String, Object>> alPostURL = new ArrayList<HashMap<String, Object>>();
            addParameter(alPostURL, Constants.HTTP_devices, sHTTP_DEVICES);
            addParameter(alPostURL, Constants.HTTP_nodes, sHTTP_NODES);

            String sBody = "";
            try {
                JSONObject jsonObj = new JSONObject();
                jsonObj.put(Constants.HTTP_content_value, sContent_value);
                sBody = "[" + jsonObj.toString() + "]";
            } catch (JSONException e) {
                e.printStackTrace();
            }
            post(sUrl + "/" + convPostUrl(alPostURL) + "/" + Constants.HTTP_contents, sBody, authorization);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String convPostUrl(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<NameValuePair> paramListPost, String sType, String parameterName, String parameterValue) {
//        if ( parameterName == null ) {
//            return;
//        }
//        if ( parameterValue == null ) {
//            paramListPost.add(new BasicNameValuePair(parameterName, ""));
//        } else {
//            Dlog.v("jino", parameterName + ": " + parameterValue);
//            paramListPost.add(new BasicNameValuePair(parameterName, parameterValue));
//        }
//    }


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


    private void post(String uri, String sBody, String authorization) {
        CustomRequest customRequest = new CustomRequest(CustomRequest.HTTP_METHOD_POST, uri, authorization, sBody, CustomRequest.SEND_METHOD_SMART);
        executeRequest(customRequest);
    }

    private OnDataSendToReslut _task_resulted_event;
    private Dialog             dialog;

    private void executeRequest(CustomRequest customRequest) {
        AsyncTask<CustomRequest, Integer, Response[]> task = null;
        try {
            task = new HttpTask(context);
            ((HttpTask) task).setOnTaskFinishedEvent(new OnTaskExecutionFinished() {

                @Override
                public void OnTaskFihishedEvent(Response[] result) {
                    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;
        }
    }

}
