package kr.co.icontrols.iotplatform;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

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.DragListView.ChangeListener;
import kr.co.icontrols.iotplatform.DragListView.RankListAdapter;
import kr.co.icontrols.iotplatform.DragListView.SwipeAndDragHelper;
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.showNotiMsg;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_GROUP_LIST;

public class GroupChangeRankActivity extends AppCompatActivity implements View.OnClickListener {

    private final String TAG = "GroupChangeRankActivity";

    private ArrayList<DeviceGroupInfo> mGroupList;

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

        mGroupList = (ArrayList<DeviceGroupInfo>) getIntent().getSerializableExtra(EXTRA_GROUP_LIST);

        RecyclerView itemRecyclerView = findViewById(R.id.recyclerview_group_list);
        itemRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        RankListAdapter adapter = new RankListAdapter(new ChangeListener() {
            @Override
            public void onChangeData() {
                findViewById(R.id.btnBack).setVisibility(View.GONE);
                findViewById(R.id.btnBackText).setVisibility(View.VISIBLE);
                findViewById(R.id.btnRight).setVisibility(View.VISIBLE);
            }
        });
        adapter.setIGroupInfoList(mGroupList);
        SwipeAndDragHelper swipeAndDragHelper = new SwipeAndDragHelper(adapter);
        ItemTouchHelper touchHelper = new ItemTouchHelper(swipeAndDragHelper);
        adapter.setTouchHelper(touchHelper);
        itemRecyclerView.setAdapter(adapter);
        touchHelper.attachToRecyclerView(itemRecyclerView);
    }

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

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

    @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.btnAlarmSetting:
                startActivity(new Intent(this, AlarmSettingActivity.class));
                break;
            case R.id.btnAppInfo:
                startActivity(new Intent(this, AppInfoActivity.class));
                break;
            case R.id.btnBack:
            case R.id.btnBackText:
                onBackPressed();
                break;
            case R.id.btnRight:
                //인덱스 변경
                for(int i = 0 ; i < mGroupList.size() ; i++) {
                    mGroupList.get(i).index = i;
                }

                displayProgress(this,"","");
                try {
                    HttpApi.changeDeviceGroupListRank(mGroupList, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.changeDeviceGroupListRank(onFailure)\n" + e.toString());
                            showNotiMsg(GroupChangeRankActivity.this, "그룹 순서를 실패하였습니다.");
                            DismissConnectDialog();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if(response.code() == HttpApi.HTTP_NO_CONTENT) {
                                WarnLogOutput(TAG, "HttpApi.changeDeviceGroupListRank(onResponse) HTTP_NO_CONTENT");
                                sortGroupRank();
                                showNotiMsg(GroupChangeRankActivity.this, "그룹 순서를 저장하였습니다.",MyGroupActivity.class);
                                DismissConnectDialog();
                            } else {
                                ErrorLogOutput(TAG, "HttpApi.changeDeviceGroupListRank(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                                DismissConnectDialog();
                                try {
                                    JSONObject json_data = new JSONObject(response.body().string());
                                    ErrorLogOutput(TAG, "HttpApi.changeDeviceGroupListRank(onResponse) body : " + json_data.toString());
                                } catch (JSONException e) {
                                    ErrorLogOutput(TAG, "HttpApi.changeDeviceGroupListRank(onResponse) JSONException : " + e.toString());
                                }
                                showNotiMsg(GroupChangeRankActivity.this, "그룹 순서를 실패하였습니다.");
                            }
                        }
                    });
                } catch (Exception e){
                    e.printStackTrace();
                    ErrorLogOutput(TAG, "HttpApi.changeDeviceGroupListRank(Exception)\n" + e.toString());
                    showNotiMsg(GroupChangeRankActivity.this, "그룹 순서를 실패하였습니다.");
                    DismissConnectDialog();
                }
                break;
        }
    }

    /**
     * UserInfo.dgroup 순서 재정렬
     */
    private void sortGroupRank() {
        for(DeviceGroupInfo g1 : mGroupList) {
            for(int i = 0 ; i < UserInfo.dgroups.size() ; i++) {
                if(g1.dgroupId.equals(UserInfo.dgroups.get(i).dgroupId)) {
                    UserInfo.dgroups.get(i).index = g1.index;
                }
            }
        }

        if(UserInfo.dgroups.size() > 1) {
            for (int i = 0; i < UserInfo.dgroups.size() - 1; i++) {
                for (int j = i + 1; j < UserInfo.dgroups.size(); j++) {
                    if (UserInfo.dgroups.get(i).index > UserInfo.dgroups.get(j).index) {
                        DeviceGroupInfo item = UserInfo.dgroups.get(j);
                        UserInfo.dgroups.remove(j);
                        UserInfo.dgroups.add(i, item);
                    }
                }
            }
        }
    }
}
