package kr.co.icontrols.iotplatform;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

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

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

import kr.co.icontrols.iotplatform.DataClass.DeviceGroupInfo;
import kr.co.icontrols.iotplatform.DataClass.UserInfo;
import kr.co.icontrols.iotplatform.utils.HttpApi;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static kr.co.icontrols.iotplatform.PopupActivity.POPUP_BUNDLE;
import static kr.co.icontrols.iotplatform.PopupActivity.POPUP_IMG_INDEX;
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.getCircleBitmap;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.getGroupImageResource;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.showNotiMsg;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_BEFORE_ACTIVITY;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_GROUP_LIST;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_01;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_BACKGROUND_00_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_BACKGROUND_01_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_BACKGROUND_02_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_BACKGROUND_03_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_BACKGROUND_04_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_BACKGROUND_05_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_BACKGROUND_06_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_BACKGROUND_07_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_BACKGROUND_08_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_BACKGROUND_09_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_00_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_01_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_02_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_03_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_04_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_05_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_06_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_07_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_08_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_09_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_LIST_COUNT_LINE;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_CHANGE_GROUP_IMG;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_INPUT_GROUP_NAME;

public class AddGroupActivity extends AppCompatActivity implements View.OnClickListener,
        TextWatcher {

    private final String TAG = "AddGroupActivity";

    private LinearLayout mLayoutGroups;
    private EditText mTxtGroupName;
    private ArrayList<DeviceGroupInfo> mGroupList;
    private int mSelectedImgIndex = GROUP_01;
    private String mBeforeActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_group);

        mLayoutGroups = findViewById(R.id.layoutGroups);
        mTxtGroupName = findViewById(R.id.txtGroupName);
        mTxtGroupName.addTextChangedListener(this);

        mGroupList = (ArrayList<DeviceGroupInfo>) getIntent().getSerializableExtra(EXTRA_GROUP_LIST);
        mBeforeActivity = getIntent().getStringExtra(EXTRA_BEFORE_ACTIVITY);
        shwoGroupList();
        changeGroupImage(mSelectedImgIndex);
    }

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

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

    @Override
    protected void onDestroy() {
        if(mGroupList!=null) {
            mGroupList.clear();
        }
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            /*
            case RESULT_INPUT_GROUP_NAME:
                if (resultCode == Activity.RESULT_OK) {
                    Bundle b = data.getBundleExtra(POPUP_BUNDLE);
                    if(b != null) {
                        ((TextView)findViewById(R.id.txtGroupName)).setText(b.getString(PopupActivity.POPUP_INPUT));
                    }
                }
                break;
            */
            case RESULT_CHANGE_GROUP_IMG:
                if (resultCode == RESULT_OK) {
                    int selected_index = data.getIntExtra(POPUP_IMG_INDEX, 1);
                    changeGroupImage(selected_index);
                }
                break;
        }
    }

    @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:
            case R.id.btnBackText:
                onBackPressed();
                break;
            case R.id.imgGroup:{
                Intent intent = new Intent(this, PopupActivity.class);
                intent.putExtra(PopupActivity.POPUP_MODE, PopupActivity.MODE_SELECT_GROUP_IMG);
                intent.putExtra(PopupActivity.POPUP_TITLE_TEXT, getString(R.string.group_image));
                intent.putExtra(POPUP_IMG_INDEX, mSelectedImgIndex);
                startActivityForResult(intent, RESULT_CHANGE_GROUP_IMG);
            }
                break;
            /*
            case R.id.txtGroupName: {
                Intent intent = new Intent(this, PopupActivity.class);
                intent.putExtra(PopupActivity.POPUP_MODE, PopupActivity.MODE_INPUT);
                Bundle b = new Bundle();
                if (isEmptyGroupName()) {
                    b.putString(PopupActivity.POPUP_INPUT, "");
                } else {
                    b.putString(PopupActivity.POPUP_INPUT, ((TextView) findViewById(R.id.txtGroupName)).getText().toString());
                }
                intent.putExtra(POPUP_BUNDLE, b);
                intent.putExtra(PopupActivity.POPUP_TITLE_TEXT, getString(R.string.group_name));
                startActivityForResult(intent, RESULT_INPUT_GROUP_NAME);
                }
                break;
            */
            case R.id.btnRight:
                boolean isExistName = false;
                for(DeviceGroupInfo d : mGroupList) {
                    if(d.friendlyName.equals(mTxtGroupName.getText().toString())) {
                        isExistName = true;
                        break;
                    }
                }

                if(isEmptyGroupName()) {
                    showNotiMsg(AddGroupActivity.this,getString(R.string.snackbar_error_need_groupname));
                } else if(isExistName) {
                    showNotiMsg(AddGroupActivity.this,getString(R.string.snackbar_error_exist_groupname));
                } else {
                    String groupImgString[] = {GROUP_IMG_00_STRING,
                            GROUP_IMG_01_STRING,GROUP_IMG_02_STRING,GROUP_IMG_03_STRING,
                            GROUP_IMG_04_STRING,GROUP_IMG_05_STRING,GROUP_IMG_06_STRING,
                            GROUP_IMG_07_STRING,GROUP_IMG_08_STRING,GROUP_IMG_09_STRING,
                    };

                    String groupBackgroundString[] = {GROUP_BACKGROUND_00_STRING,
                            GROUP_BACKGROUND_01_STRING,GROUP_BACKGROUND_02_STRING,GROUP_BACKGROUND_03_STRING,
                            GROUP_BACKGROUND_04_STRING,GROUP_BACKGROUND_05_STRING,GROUP_BACKGROUND_06_STRING,
                            GROUP_BACKGROUND_07_STRING,GROUP_BACKGROUND_08_STRING,GROUP_BACKGROUND_09_STRING,
                    };

                    displayProgress(this,"","");
                    try {
                        HttpApi.registerDeviceGroup(mTxtGroupName.getText().toString(),
                                groupImgString[mSelectedImgIndex],
                                groupBackgroundString[mSelectedImgIndex],
                                new Callback() {
                                    @Override
                                    public void onFailure(Call call, IOException e) {
                                        e.printStackTrace();
                                        ErrorLogOutput(TAG, "HttpApi.registerDeviceGroup(onFailure)\n" + e.toString());
                                        showNotiMsg(AddGroupActivity.this,"그룹 추가를 실패하였습니다.");
                                        DismissConnectDialog();
                                    }

                                    @Override
                                    public void onResponse(Call call, Response response) throws IOException {
                                        if(response.code() == HttpApi.HTTP_NO_CONTENT) {
                                            UserInfo.dgroups.clear();
                                            WarnLogOutput(TAG, "HttpApi.registerDeviceGroup(onResponse) HTTP_NO_CONTENT");
                                            if(mBeforeActivity != null && mBeforeActivity.equals("LightRegisterDeviceFinishActivity")) {
                                                showNotiMsg(AddGroupActivity.this,"그룹를 추가하였습니다.",true);
                                            } else {
                                                showNotiMsg(AddGroupActivity.this,"그룹를 추가하였습니다.",MyGroupActivity.class);
                                            }
                                            DismissConnectDialog();
                                        } else {
                                            ErrorLogOutput(TAG, "HttpApi.registerDeviceGroup(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                                            showNotiMsg(AddGroupActivity.this,"그룹 추가를 실패하였습니다.");
                                            DismissConnectDialog();
                                            try {
                                                JSONObject json_data = new JSONObject(response.body().string());
                                                ErrorLogOutput(TAG, "HttpApi.registerDeviceGroup(onResponse) body : " + json_data.toString());
                                            } catch (JSONException e) {
                                                ErrorLogOutput(TAG, "HttpApi.registerDeviceGroup(onResponse) JSONException : " + e.toString());
                                            }
                                        }
                                    }
                                });
                    } catch (Exception e) {
                        e.printStackTrace();
                        ErrorLogOutput(TAG, "HttpApi.registerDeviceGroup(Exception)\n" + e.toString());
                        showNotiMsg(AddGroupActivity.this,"그룹 추가를 실패하였습니다.");
                        DismissConnectDialog();
                    }
                }
                break;
        }
    }

    private boolean isEmptyGroupName() {
        return (mTxtGroupName.getText().toString().length() == 0 || mTxtGroupName.getText().toString().equals(getString(R.string.hint_input_text)));
    }

    private void changeGroupImage(final int index) {
        int groupImgResource[] = {R.drawable.invisiableimage,
                R.drawable.img_group_01,R.drawable.img_group_02,R.drawable.img_group_03,
                R.drawable.img_group_04,R.drawable.img_group_05,R.drawable.img_group_06,
                R.drawable.img_group_07,R.drawable.img_group_08,R.drawable.img_group_09
        };
        mSelectedImgIndex = index;
        ((ImageView)findViewById(R.id.imgGroup)).setImageBitmap(getCircleBitmap(groupImgResource[mSelectedImgIndex]));
    }

    private void shwoGroupList() {
        LinearLayout layoutHorizontal = null;
        int lineCount = 0;
        for(int i = 0; i < mGroupList.size(); i++){
            if(i%GROUP_LIST_COUNT_LINE==0) {
                lineCount = 0;
                layoutHorizontal = new LinearLayout(this);
                LinearLayout.LayoutParams lparam = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                layoutHorizontal.setLayoutParams(lparam);
                layoutHorizontal.setOrientation(LinearLayout.HORIZONTAL);
                mLayoutGroups.addView(layoutHorizontal);

                LinearLayout spacelayout = new LinearLayout(this);
                LinearLayout.LayoutParams slparam = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                slparam.weight = 1;
                spacelayout.setLayoutParams(slparam);
                spacelayout.setOrientation(LinearLayout.HORIZONTAL);
                layoutHorizontal.addView(spacelayout);
            }
            
            if(layoutHorizontal != null) {
                lineCount++;
                final View child = getLayoutInflater().inflate(R.layout.listview_horizontal_group_item, null);
                final TextView txtGroupName = child.findViewById(R.id.txtGroup);
                final ImageView imgGroup = child.findViewById(R.id.imgGroup);
                txtGroupName.setText(mGroupList.get(i).friendlyName);
                imgGroup.setImageBitmap(getCircleBitmap(getGroupImageResource(mGroupList.get(i).icon)));
                layoutHorizontal.addView(child);

                LinearLayout spacelayout = new LinearLayout(this);
                LinearLayout.LayoutParams slparam = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                slparam.weight = 1;
                spacelayout.setLayoutParams(slparam);
                spacelayout.setOrientation(LinearLayout.HORIZONTAL);
                layoutHorizontal.addView(spacelayout);
            }

            if(i == mGroupList.size()-1 && lineCount < GROUP_LIST_COUNT_LINE) {
                while(lineCount < GROUP_LIST_COUNT_LINE) {
                    lineCount++;
                    final View child = getLayoutInflater().inflate(R.layout.listview_horizontal_group_item, null);
                    final TextView txtGroupName = child.findViewById(R.id.txtGroup);
                    final ImageView imgGroup = child.findViewById(R.id.imgGroup);
                    txtGroupName.setVisibility(View.INVISIBLE);
                    imgGroup.setVisibility(View.INVISIBLE);
                    layoutHorizontal.addView(child);

                    LinearLayout spacelayout = new LinearLayout(this);
                    LinearLayout.LayoutParams slparam = new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                    slparam.weight = 1;
                    spacelayout.setLayoutParams(slparam);
                    spacelayout.setOrientation(LinearLayout.HORIZONTAL);
                    layoutHorizontal.addView(spacelayout);
                }
            }
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if(mTxtGroupName.length() > 0) {
            findViewById(R.id.btnBack).setVisibility(View.GONE);
            findViewById(R.id.btnBackText).setVisibility(View.VISIBLE);
            findViewById(R.id.btnRight).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.btnBack).setVisibility(View.VISIBLE);
            findViewById(R.id.btnBackText).setVisibility(View.GONE);
            findViewById(R.id.btnRight).setVisibility(View.INVISIBLE);
        }
    }
}