package kr.co.icontrols.iotplatform;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import kr.co.icontrols.iotplatform.DataClass.KakaoLocationInfo;
import kr.co.icontrols.iotplatform.DataClass.UserInfo;
import kr.co.icontrols.iotplatform.adapter.KaKaoLoctionAdapter;
import kr.co.icontrols.iotplatform.utils.HttpApi;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static kr.co.icontrols.iotplatform.utils.CommonUtils.DismissConnectDialog;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.ErrorLogOutput;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.ForceDismissConnectDialog;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.WarnLogOutput;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.displayProgress;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.setupUI;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.showNotiMsg;
import static kr.co.icontrols.iotplatform.utils.HttpApi.HTTP_CONFLICT;
import static kr.co.icontrols.iotplatform.utils.HttpApi.HTTP_CREATED;
import static kr.co.icontrols.iotplatform.utils.HttpApi.HTTP_NO_CONTENT;
import static kr.co.icontrols.iotplatform.utils.HttpApi.HTTP_OK;

public class RegisterLocationActivity extends AppCompatActivity implements View.OnClickListener {
    private final String TAG = "RegisterLocationActivity";
    private KaKaoLoctionAdapter mKaKaoLoctionAdapter = new KaKaoLoctionAdapter();
    private KakaoLocationInfo kakaoLocationInfo = null;
    private Button btnRegister;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_location);
        setupUI(this,findViewById(R.id.layoutMain));

        btnRegister = findViewById(R.id.btnRegister);


        ListView listView = findViewById(R.id.listView);
        listView.setAdapter(mKaKaoLoctionAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                kakaoLocationInfo = (KakaoLocationInfo) parent.getItemAtPosition(position);
                mKaKaoLoctionAdapter.setSelected(position);
                btnRegister.setVisibility(View.VISIBLE);
            }
        });
    }

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

    @Override
    protected void onPause() {
        ForceDismissConnectDialog();
        super.onPause();
    }

    @Override
    protected void onDestroy() {

        if(mKaKaoLoctionAdapter!=null) {
            mKaKaoLoctionAdapter.removeAllItem();
        }

        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        /*
        final View fv = v;
        fv.setEnabled(false);
        Timer buttonTimer = new Timer();
        buttonTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            fv.setEnabled(true);
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {

                        }
                    }
                });
            }
        }, 500);
        */

        switch (v.getId()) {
            case R.id.btnBack:
                onBackPressed();
                break;
            case R.id.btnSearch:
                btnRegister.setVisibility(View.INVISIBLE);
                kakaoLocationInfo = null;
                mKaKaoLoctionAdapter.removeAllItem();
                mKaKaoLoctionAdapter.notifyDataSetChanged();

                final String input = ((TextView)findViewById(R.id.txtInput)).getText().toString();
                try {
                    displayProgress(RegisterLocationActivity.this,"","");
                    HttpApi.getLocationInfo(input, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.getLocationInfo(onFailure)\n" + e.toString());
                            DismissConnectDialog();
                            showNotiMsg(RegisterLocationActivity.this,"지역 검색을 실패하였습니다.");
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if(response.code() == HTTP_OK) {
                                WarnLogOutput(TAG, "HttpApi.getLocationInfo(onResponse) : HTTP_OK");
                                try {
                                    JSONObject json_data = new JSONObject(response.body().string());
                                    WarnLogOutput(TAG, "HttpApi.getLocationInfo(onResponse) body : " + json_data.toString());

                                    JSONArray jarrayAll = new JSONArray(json_data.getString("documents"));

                                    for (int i = 0; i < jarrayAll.length(); i++) {
                                        JSONObject jObject = jarrayAll.getJSONObject(i);

                                        KakaoLocationInfo item = new KakaoLocationInfo();
                                        if(!jObject.isNull("address")) {
                                            JSONObject subJObject = new JSONObject(jObject.getString("address"));
                                            item.address_name = jObject.isNull("address_name") ? "" : jObject.getString("address_name");
                                            item.b_code = subJObject.isNull("b_code") ? "" : subJObject.getString("b_code");
                                            item.h_code = subJObject.isNull("h_code") ? "" : subJObject.getString("h_code");
                                            item.main_address_no = subJObject.isNull("main_address_no") ? "" : subJObject.getString("main_address_no");
                                            item.mountain_yn = subJObject.isNull("mountain_yn") ? "" : subJObject.getString("mountain_yn");
                                            item.region_1depth_name = subJObject.isNull("region_1depth_name") ? "" : subJObject.getString("region_1depth_name");
                                            item.region_2depth_name = subJObject.isNull("region_2depth_name") ? "" : subJObject.getString("region_2depth_name");
                                            item.region_3depth_h_name = subJObject.isNull("region_3depth_h_name") ? "" : subJObject.getString("region_3depth_h_name");
                                            item.region_3depth_name = subJObject.isNull("region_3depth_name") ? "" : subJObject.getString("region_3depth_name");
                                            item.sub_address_no = subJObject.isNull("sub_address_no") ? "" : subJObject.getString("sub_address_no");
                                            item.x = jObject.isNull("x") ? "" : jObject.getString("x");
                                            item.y = jObject.isNull("y") ? "" : jObject.getString("y");
                                            item.address_type = jObject.isNull("address_type") ? "" : jObject.getString("address_type");
                                            item.road_address = jObject.isNull("road_address") ? "" : jObject.getString("road_address");
                                        } else if(!jObject.isNull("road_address")) {
                                            JSONObject subJObject = new JSONObject(jObject.getString("road_address"));
                                            item.address_name = jObject.isNull("address_name") ? "" : jObject.getString("address_name");
                                            item.region_1depth_name = subJObject.isNull("region_1depth_name") ? "" : subJObject.getString("region_1depth_name");
                                            item.region_2depth_name = subJObject.isNull("region_2depth_name") ? "" : subJObject.getString("region_2depth_name");
                                            item.region_3depth_h_name = subJObject.isNull("region_3depth_h_name") ? "" : subJObject.getString("region_3depth_h_name");
                                            item.region_3depth_name = subJObject.isNull("region_3depth_name") ? "" : subJObject.getString("region_3depth_name");

                                            //동이 있는 경우 동 추가.
                                            item.address_name += item.region_3depth_name.isEmpty()?"":"("+item.region_3depth_name+")";

                                            item.x = jObject.isNull("x") ? "" : jObject.getString("x");
                                            item.y = jObject.isNull("y") ? "" : jObject.getString("y");
                                        }

                                        if(!item.region_3depth_name.isEmpty() || !item.region_3depth_h_name.isEmpty()) {
                                            mKaKaoLoctionAdapter.addItem(item);
                                        }
                                    }

                                    //UI 업데이트
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if(mKaKaoLoctionAdapter.getCount() == 0) {
                                                showNotiMsg(RegisterLocationActivity.this,getString(R.string.snackbar_error_not_found_location));
                                            } else {
                                                mKaKaoLoctionAdapter.notifyDataSetChanged();
                                            }
                                            DismissConnectDialog();
                                        }
                                    });
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    ErrorLogOutput(TAG, "HttpApi.getLocationInfo(JSONException)\n" + e.toString());
                                    showNotiMsg(RegisterLocationActivity.this,"지역 검색을 실패하였습니다.");
                                    DismissConnectDialog();
                                }
                            } else {
                                ErrorLogOutput(TAG, "HttpApi.getLocationInfo(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                                DismissConnectDialog();
                                showNotiMsg(RegisterLocationActivity.this,"지역 검색을 실패하였습니다.");
                                try {
                                    JSONObject json_data = new JSONObject(response.body().string());
                                    ErrorLogOutput(TAG, "HttpApi.getLocationInfo(onResponse) body : " + json_data.toString());
                                } catch (JSONException e) {
                                    ErrorLogOutput(TAG, "HttpApi.getLocationInfo(onResponse) JSONException : " + e.toString());
                                }
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    DismissConnectDialog();
                    showNotiMsg(RegisterLocationActivity.this,"지역 검색을 실패하였습니다.");
                    ErrorLogOutput(TAG, "HttpApi.getLocationInfo(Exception)\n" + e.toString());
                }
                break;
            case R.id.btnDeleteInput:
                ((TextView)findViewById(R.id.txtInput)).setText("");
                break;
            case R.id.btnRegister:
                if(kakaoLocationInfo != null) {
                    if (UserInfo.location.size() > 0) {
                        modifyLocation(kakaoLocationInfo);
                    } else {
                        registerLocation(kakaoLocationInfo);
                    }
                }
                break;
        }
    }

    private void registerLocation(final KakaoLocationInfo item) {
        try {
            displayProgress(RegisterLocationActivity.this,"","");
            HttpApi.registerLocationInfo(item.y,
                    item.x,
                    item.region_1depth_name,
                    item.region_2depth_name,
                    item.region_3depth_name.isEmpty()?item.region_3depth_h_name:item.region_3depth_name,
                    new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.registerLocationInfo(onFailure)\n" + e.toString());
                            showNotiMsg(RegisterLocationActivity.this,getString(R.string.snackbar_error_reg_location));
                            DismissConnectDialog();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if(response.code() == HTTP_NO_CONTENT) {
                                WarnLogOutput(TAG, "HttpApi.registerLocationInfo(onResponse) : HTTP_CREATED");
                                UserInfo.updateTimeUserInfo = 0;
                                UserInfo.updateTimeWeatherInfo = 0;
                                showNotiMsg(RegisterLocationActivity.this,getString(R.string.snackbar_successed_reg_location),MainActivity.class);
                            } else if(response.code() == HTTP_CONFLICT) {

                            } else {
                                ErrorLogOutput(TAG, "HttpApi.registerLocationInfo(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                                try {
                                    JSONObject json_data = new JSONObject(response.body().string());
                                    ErrorLogOutput(TAG, "HttpApi.registerLocationInfo(onResponse) body : " + json_data.toString());
                                } catch (JSONException e) {
                                    ErrorLogOutput(TAG, "HttpApi.registerLocationInfo(onResponse) JSONException : " + e.toString());
                                }
                                showNotiMsg(RegisterLocationActivity.this,getString(R.string.snackbar_error_reg_location));
                            }
                            DismissConnectDialog();
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
            ErrorLogOutput(TAG, "HttpApi.registerLocationInfo(Exception)\n" + e.toString());
            showNotiMsg(RegisterLocationActivity.this,getString(R.string.snackbar_error_reg_location));
            DismissConnectDialog();
        }
    }

    private void modifyLocation(final KakaoLocationInfo item) {
        try {
            displayProgress(RegisterLocationActivity.this,"","");
            HttpApi.modifyLocationInfo(UserInfo.location.get(0).locationId,
                    item.y,
                    item.x,
                    item.region_1depth_name,
                    item.region_2depth_name,
                    item.region_3depth_name.isEmpty()?item.region_3depth_h_name:item.region_3depth_name,
                    new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.modifyLocationInfo(onFailure)\n" + e.toString());
                            showNotiMsg(RegisterLocationActivity.this,getString(R.string.snackbar_error_reg_location));
                            DismissConnectDialog();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if(response.code() == HTTP_NO_CONTENT) {
                                WarnLogOutput(TAG, "HttpApi.modifyLocationInfo(onResponse) : HTTP_CREATED");
                                UserInfo.updateTimeUserInfo = 0;
                                UserInfo.updateTimeWeatherInfo = 0;
                                showNotiMsg(RegisterLocationActivity.this,getString(R.string.snackbar_successed_reg_location),MainActivity.class);
                            } else if(response.code() == HTTP_CONFLICT) {

                            } else {
                                ErrorLogOutput(TAG, "HttpApi.modifyLocationInfo(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                                try {
                                    JSONObject json_data = new JSONObject(response.body().string());
                                    ErrorLogOutput(TAG, "HttpApi.modifyLocationInfo(onResponse) body : " + json_data.toString());
                                } catch (JSONException e) {
                                    ErrorLogOutput(TAG, "HttpApi.modifyLocationInfo(onResponse) JSONException : " + e.toString());
                                }
                                showNotiMsg(RegisterLocationActivity.this,getString(R.string.snackbar_error_reg_location));
                            }
                            DismissConnectDialog();
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
            ErrorLogOutput(TAG, "HttpApi.modifyLocationInfo(Exception)\n" + e.toString());
            showNotiMsg(RegisterLocationActivity.this,getString(R.string.snackbar_error_reg_location));
            DismissConnectDialog();
        }
    }
}