package kr.co.icontrols.iotplatform;

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

import android.app.Activity;
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.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;

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.MemberInfo;
import kr.co.icontrols.iotplatform.DataClass.UserInfo;
import kr.co.icontrols.iotplatform.adapter.MemberAdapter;
import kr.co.icontrols.iotplatform.utils.CommonUtils;
import kr.co.icontrols.iotplatform.utils.DownloadImageTask;
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.showNotiMsg;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_CHANGE_GROUP_IMG;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_CONFIRM_DELETE_MEMBER;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_INPUT_GROUP_NAME;
import static kr.co.icontrols.iotplatform.utils.HttpApi.HTTP_OK;

public class AdminMemberActivity extends AppCompatActivity implements View.OnClickListener {
    private final String TAG = "AdminMemberActivity";

    private MemberAdapter mMemberAdapter = new MemberAdapter(this);
    private ListView mMemberList;

    public static String sSelectedMemberId = "";

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

        ((TextView)findViewById(R.id.txtName)).setText(UserInfo.nickname);

        mMemberList = findViewById(R.id.listMember);
        mMemberList.setAdapter(mMemberAdapter);
        if(UserInfo.profile != null && !UserInfo.profile.isEmpty()) {
            new DownloadImageTask(findViewById(R.id.imgProfile)).execute(UserInfo.profile);
        } else {
            ((ImageView)findViewById(R.id.imgProfile)).setImageResource(R.drawable.profile_thum_176);
        }
        getMemberList();
    }

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

    @Override
    protected void onDestroy() {
        if(mMemberAdapter != null) {
            mMemberAdapter.removeAllItem();
        }

        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_CONFIRM_DELETE_MEMBER:
                if (resultCode == Activity.RESULT_OK) {
                    try {
                        displayProgress(AdminMemberActivity.this,"","");
                        HttpApi.deleteGuest(sSelectedMemberId, new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                e.printStackTrace();
                                ErrorLogOutput(TAG, "HttpApi.deleteGuest(onFailure)\n" + e.toString());
                                showNotiMsg(AdminMemberActivity.this,"맴버 삭제를 실패하였습니다.");
                                DismissConnectDialog();
                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                if(response.code() == HttpApi.HTTP_NO_CONTENT) {
                                    WarnLogOutput(TAG, "HttpApi.deleteGuest(onResponse) HTTP_NO_CONTENT");
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            mMemberAdapter.removeItem(sSelectedMemberId);
                                            mMemberAdapter.notifyDataSetChanged();
                                            showNotiMsg(AdminMemberActivity.this,"맴버를 삭제하였습니다.");

                                            if(mMemberAdapter.getCount() == 0) {
                                                findViewById(R.id.layoutMembers).setVisibility(View.INVISIBLE);
                                            } else {
                                                ((TextView)findViewById(R.id.txtMemberCount)).setText(String.format("멤버(%d명)",mMemberAdapter.getCount()));
                                                findViewById(R.id.layoutMembers).setVisibility(View.VISIBLE);
                                            }

                                            DismissConnectDialog();
                                        }
                                    });
                                } else {
                                    ErrorLogOutput(TAG, "HttpApi.deleteGuest(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                                    showNotiMsg(AdminMemberActivity.this,"맴버 삭제를 실패하였습니다.");
                                    DismissConnectDialog();
                                    try {
                                        JSONObject json_data = new JSONObject(response.body().string());
                                        ErrorLogOutput(TAG, "HttpApi.deleteGuest(onResponse) body : " + json_data.toString());
                                    } catch (JSONException e) {
                                        ErrorLogOutput(TAG, "HttpApi.deleteGuest(onResponse) JSONException : " + e.toString());
                                    }
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        showNotiMsg(AdminMemberActivity.this,"맴버 삭제를 실패하였습니다.");
                        DismissConnectDialog();
                        ErrorLogOutput(TAG, "HttpApi.deleteGuest(Exception)\n" + e.toString());
                    }

                } else {
                    sSelectedMemberId = "";
                }
                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:
                onBackPressed();
                break;
            case R.id.btnInviteMember:
                //startActivity(new Intent(this, InviteMemberActivity.class));
                Intent intent = new Intent(this, InviteMemberInputActivity.class);
                intent.putExtra("MODE","email");
                startActivity(intent);
                break;
        }
    }

    private void getMemberList() {
        try {
            displayProgress(AdminMemberActivity.this,"","");
            HttpApi.getGuestList(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    ErrorLogOutput(TAG, "HttpApi.getGuestList(onFailure)\n" + e.toString());
                    showNotiMsg(AdminMemberActivity.this,"맴버 획득를 실패하였습니다.");
                    DismissConnectDialog();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if(response.code() == HTTP_OK) {
                        WarnLogOutput(TAG, "HttpApi.getGuestList(onResponse) : HTTP_OK");
                        try {
                            JSONObject json_data = new JSONObject(response.body().string());
                            JSONArray jarrayAll = new JSONArray(json_data.getString("results"));
                            for (int i = 0; i < jarrayAll.length(); i++) {
                                JSONObject jObject = jarrayAll.getJSONObject(i);
                                MemberInfo item = new MemberInfo(jObject.isNull("customerId") ? "" : jObject.getString("customerId"),
                                        jObject.isNull("nickname") ? "" : jObject.getString("nickname"),
                                        jObject.isNull("profile") ? "" : jObject.getString("profile"));

                                mMemberAdapter.addItem(item);
                            }

                            //UI 업데이트
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if(mMemberAdapter.getCount() == 0) {
                                        //findViewById(R.id.btnInviteMember).setVisibility(View.VISIBLE);
                                        findViewById(R.id.layoutMembers).setVisibility(View.INVISIBLE);
                                        showNotiMsg(AdminMemberActivity.this,"맴버가 존재하지 않습니다.");
                                    } else {
                                        mMemberAdapter.notifyDataSetChanged();
                                        ((TextView)findViewById(R.id.txtMemberCount)).setText(String.format("멤버(%d명)",mMemberAdapter.getCount()));
                                        //findViewById(R.id.btnInviteMember).setVisibility(View.INVISIBLE);
                                        findViewById(R.id.layoutMembers).setVisibility(View.VISIBLE);
                                        showNotiMsg(AdminMemberActivity.this,"맴버 목록을 획득하였습니다.");
                                    }
                                    DismissConnectDialog();
                                }
                            });

                        } catch (JSONException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.getGuestList(JSONException)\n" + e.toString());
                            showNotiMsg(AdminMemberActivity.this,"맴버 획득를 실패하였습니다.");
                            DismissConnectDialog();
                        }
                    } else {
                        ErrorLogOutput(TAG, "HttpApi.getGuestList(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                        showNotiMsg(AdminMemberActivity.this,"맴버 획득를 실패하였습니다.");
                        DismissConnectDialog();
                        try {
                            JSONObject json_data = new JSONObject(response.body().string());
                            ErrorLogOutput(TAG, "HttpApi.getGuestList(onResponse) body : " + json_data.toString());
                        } catch (JSONException e) {
                            ErrorLogOutput(TAG, "HttpApi.getGuestList(onResponse) JSONException : " + e.toString());
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            ErrorLogOutput(TAG, "HttpApi.getGuestList(Exception)\n" + e.toString());
            showNotiMsg(AdminMemberActivity.this,"맴버 획득를 실패하였습니다.");
            DismissConnectDialog();
        }
    }
}