package kr.co.icontrols.iotplatform.adapter;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

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.DeviceGroupInfo;
import kr.co.icontrols.iotplatform.DataClass.DeviceInfo;
import kr.co.icontrols.iotplatform.DataClass.UserInfo;
import kr.co.icontrols.iotplatform.Database.DBUtil;
import kr.co.icontrols.iotplatform.LightDetailActivity;
import kr.co.icontrols.iotplatform.LightRegisterDeviceActivity;
import kr.co.icontrols.iotplatform.PopupActivity;
import kr.co.icontrols.iotplatform.R;
import kr.co.icontrols.iotplatform.utils.HttpApi;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static com.amazonaws.mobile.auth.core.internal.util.ThreadUtils.runOnUiThread;
import static kr.co.icontrols.iotplatform.Database.DatabaseHelper.TABLE_DEVICE_RANK;
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.DebugLogOutput;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.ErrorLogOutput;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.WarnLogOutput;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.getCircleBitmap;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.getGroupBackgournResourceWithIcon;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.getGroupImageIndex;
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.DEFAULT_RANK;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_DEVICE_INFO;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_CHANGE_GROUP_IMG;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_INPUT_GROUP_NAME;
import static kr.co.icontrols.iotplatform.utils.HttpApi.HTTP_OK;

public class MyGroupTabPagerAdapter extends PagerAdapter {
    private final String TAG = "MyGroupTabPagerAdapter";

    private ArrayList<DeviceGroupInfo> mListGroup;
    private Activity mActivity;

    public interface PressSettingButton {
        void showGroupSettingMenu();
        void goToAddDevice();
    }

    private PressSettingButton pressSettingButton;

    public MyGroupTabPagerAdapter(Activity activity, ArrayList<DeviceGroupInfo> list, PressSettingButton pressSettingButton) {
        this.mActivity = activity;
        this.mListGroup = list;
        this.pressSettingButton = pressSettingButton;
    }

    @Override
    public int getCount() {
        return mListGroup.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return (view ==(View)object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        ViewGroup viewGroup = (ViewGroup) mActivity.getLayoutInflater().inflate(
                R.layout.layout_my_group_tab_viewpager, null);

        final RelativeLayout layoutTopRelativeLayout = viewGroup.findViewById(R.id.layoutTop);
        final LinearLayout layoutRegisterDevice = viewGroup.findViewById(R.id.layoutRegisterDevice);
        final LinearLayout btnRegisterDevice = viewGroup.findViewById(R.id.btnRegisterDevice);
        final LinearLayout layoutListView = viewGroup.findViewById(R.id.layoutListView);
        final LinearLayout layoutGroupName = viewGroup.findViewById(R.id.layoutGroupName);
        final LinearLayout layoutAllOnOff = viewGroup.findViewById(R.id.layoutAllOnOff);
        final ListView listView = viewGroup.findViewById(R.id.listView);
        final ImageView imgGroup = viewGroup.findViewById(R.id.imgGroup);
        final TextView txtGroupName = viewGroup.findViewById(R.id.txtGroupName);
        final TextView txtDeviceCount = viewGroup.findViewById(R.id.txtDeviceCount);
        final TextView txtAddDevice = viewGroup.findViewById(R.id.txtAddDevice);
        final TextView txtAllOnOff = viewGroup.findViewById(R.id.txtAllOnOff);
        final ImageButton btnSetting = viewGroup.findViewById(R.id.btnSetting);


        if(UserInfo.deviceCount > 0) {
            txtAddDevice.setText(mActivity.getString(R.string.add_device_for_group));
            btnRegisterDevice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(pressSettingButton != null) {
                        pressSettingButton.goToAddDevice();
                    }
                }
            });
        } else {
            txtAddDevice.setText(mActivity.getString(R.string.add_device));
            btnRegisterDevice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mActivity.startActivity(new Intent(mActivity, LightRegisterDeviceActivity.class));
                }
            });
        }

        btnSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(pressSettingButton != null) {
                    pressSettingButton.showGroupSettingMenu();
                }
            }
        });

        layoutTopRelativeLayout.setBackgroundResource(getGroupBackgournResourceWithIcon(mListGroup.get(position).icon));
        imgGroup.setImageBitmap(getCircleBitmap(getGroupImageResource(mListGroup.get(position).icon)));
        txtGroupName.setText(mListGroup.get(position).friendlyName);
        final int pos = position;
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final DeviceInfo item = (DeviceInfo) parent.getItemAtPosition(position);
                if(item.dgroupName.isEmpty() && item.dgroupId.isEmpty()) {
                    item.dgroupName = mListGroup.get(pos).friendlyName;
                    item.dgroupId = mListGroup.get(pos).dgroupId;
                }
                Intent intent = new Intent(mActivity, LightDetailActivity.class);
                intent.putExtra(EXTRA_DEVICE_INFO, (Parcelable) item);
                mActivity.startActivity(intent);
            }
        });

        if(position != 0) {
            layoutGroupName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mActivity, PopupActivity.class);
                    intent.putExtra(PopupActivity.POPUP_MODE, PopupActivity.MODE_INPUT);
                    Bundle b = new Bundle();
                    if (txtGroupName.getText().toString().isEmpty()) {
                        b.putString(PopupActivity.POPUP_INPUT, "");
                    } else {
                        b.putString(PopupActivity.POPUP_INPUT, txtGroupName.getText().toString());
                    }
                    intent.putExtra(POPUP_BUNDLE, b);
                    intent.putExtra(PopupActivity.POPUP_TITLE_TEXT, mActivity.getString(R.string.change_group_name));
                    mActivity.startActivityForResult(intent, RESULT_INPUT_GROUP_NAME);
                }
            });
        }

        imgGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                {
                    Intent intent = new Intent(mActivity, PopupActivity.class);
                    intent.putExtra(PopupActivity.POPUP_MODE, PopupActivity.MODE_SELECT_GROUP_IMG);
                    intent.putExtra(PopupActivity.POPUP_TITLE_TEXT, mActivity.getString(R.string.group_image));
                    intent.putExtra(POPUP_IMG_INDEX, getGroupImageIndex(mListGroup.get(position).icon));
                    mActivity.startActivityForResult(intent, RESULT_CHANGE_GROUP_IMG);
                }
            }
        });


        try{
            HttpApi.getDeviceListInDeviceGroup(mListGroup.get(position).dgroupId, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    ErrorLogOutput(TAG, "HttpApi.getDeviceListInDeviceGroup(onFailure)\n" + e.toString());
                    showNotiMsg(mActivity,"스마트 조명 목록 조회에 실패하였습니다");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if(response.code() == HTTP_OK) {
                        WarnLogOutput(TAG, "HttpApi.getDeviceListInDeviceGroup(onResponse) : HTTP_OK");
                        final ArrayList<DeviceInfo> deviceInfoList = new ArrayList<>();
                        try {
                            JSONObject json_data = new JSONObject(response.body().string());
                            JSONArray jarrayAll = new JSONArray(json_data.getString("devices"));

                            for (int i = 0; i < jarrayAll.length(); i++) {
                                JSONObject jObject = jarrayAll.getJSONObject(i);
                                DeviceInfo item = new DeviceInfo(
                                        jObject.isNull("deviceId") ? "" : jObject.getString("deviceId"),
                                        jObject.isNull("deviceType") ? "" : jObject.getString("deviceType"),
                                        jObject.isNull("friendlyName") ? "" : jObject.getString("friendlyName"),
                                        jObject.isNull("sharedFriendlyName") ? "" : jObject.getString("sharedFriendlyName"),
                                        jObject.isNull("dgroupId") ? "" : jObject.getString("dgroupId"),
                                        jObject.isNull("dgroupName") ? "" : jObject.getString("dgroupName"),
                                        jObject.isNull("ownerId") ? "" : jObject.getString("ownerId"),
                                        DEFAULT_RANK,
                                        DEFAULT_RANK
                                );

                                DeviceInfo localDbItem = DBUtil.getDeviceInfoForId(TABLE_DEVICE_RANK, item.deviceId);
                                if (localDbItem != null) {
                                    item.rank = localDbItem.rank;
                                    item.groupRank = localDbItem.groupRank;
                                }

                                deviceInfoList.add(item);
                            }

                            if(deviceInfoList.size() > 1) {
                                for(int i = 0 ; i < deviceInfoList.size()-1 ; i ++) {
                                    for(int j = i+1 ; j < deviceInfoList.size() ; j ++) {
                                        if(deviceInfoList.get(i).groupRank > deviceInfoList.get(j).groupRank) {
                                            DeviceInfo item = deviceInfoList.get(j);
                                            deviceInfoList.remove(j);
                                            deviceInfoList.add(i,item);
                                        }
                                    }
                                }
                            }

                            final int deviceCount = json_data.isNull("count") ? 0 : json_data.getInt("count");

                            for(int i = 0 ; i < UserInfo.dgroups.size() ; i++) {
                                if(UserInfo.dgroups.get(i).dgroupId.equals(mListGroup.get(position).dgroupId)){
                                    UserInfo.dgroups.get(i).deviceCount = deviceCount;
                                }
                            }

                            //UI 업데이트
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if(deviceInfoList.size() == 0) {
                                        layoutRegisterDevice.setVisibility(View.VISIBLE);
                                        layoutListView.setVisibility(View.GONE);
                                    } else {
                                        layoutRegisterDevice.setVisibility(View.GONE);
                                        layoutListView.setVisibility(View.VISIBLE);
                                        final DeviceListAdapter deviceListAdapter = new DeviceListAdapter(mActivity, deviceInfoList,mListGroup.get(position).friendlyName);
                                        listView.setAdapter(deviceListAdapter);

                                        layoutAllOnOff.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                deviceListAdapter.setOnOff();
                                            }
                                        });
                                    }
                                    txtDeviceCount.setText(deviceCount+"개 스마트 조명 등록");

                                }
                            });

                        } catch (JSONException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.getDeviceListInDeviceGroup(JSONException)\n" + e.toString());
                        }
                    } else {
                        ErrorLogOutput(TAG, "HttpApi.getDeviceListInDeviceGroup(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                        showNotiMsg(mActivity,"스마트 조명 목록 조회에 실패하였습니다" + " : " + response.code());
                        try {
                            JSONObject json_data = new JSONObject(response.body().string());
                            ErrorLogOutput(TAG, "HttpApi.getDeviceListInDeviceGroup(onResponse) body : " + json_data.toString());
                        } catch (JSONException e) {
                            ErrorLogOutput(TAG, "HttpApi.getDeviceListInDeviceGroup(onResponse) JSONException : " + e.toString());
                        }
                    }
                }
            });
        } catch(Exception e){
            e.printStackTrace();
            ErrorLogOutput(TAG, "HttpApi.getDeviceListInDeviceGroup(Exception)\n" + e.toString());
            showNotiMsg(mActivity,"스마트 조명 목록 조회에 실패하였습니다");
        }

        container.addView(viewGroup);

        return viewGroup;
    }
        @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @Override
    public void destroyItem(ViewGroup collection, int position, Object view) {
        //must be overridden else throws exception as not overridden.
        DebugLogOutput(TAG, "destroyItem : " + collection.getChildCount()+"");
        collection.removeView((View) view);
    }

    public void removeAll() {
        if(mListGroup != null) {
            mListGroup.clear();
        }
    }
}
