package kr.co.icontrols.iotplatform;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

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

import java.io.IOException;

import kr.co.icontrols.iotplatform.cognito.AppHelper;
import kr.co.icontrols.iotplatform.utils.CommonUtils;
import kr.co.icontrols.iotplatform.utils.HttpApi;
import kr.co.icontrols.iotplatform.utils.SharedPrefUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static kr.co.icontrols.iotplatform.utils.CommonUtils.ErrorLogOutput;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_BACKGROUND_09_STRING;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_IMG_09_STRING;
import static kr.co.icontrols.iotplatform.utils.HttpApi.HTTP_NO_CONTENT;

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

    final int U_1 = 0;
    final int U_2 = 1;
    final int U_3 = 2;
    final int U_4 = 3;
    final int U_5 = 4;
    final int U_6 = 5;
    final int M_1 = 6;
    final int M_2 = 7;
    final int M_3 = 8;
    final int M_4 = 9;
    final int M_5 = 10;
    final int M_6 = 11;
    final int M_7 = 12;
    final int M_8 = 13;
    final int M_9 = 14;
    final int M_10 = 15;
    final int G_1 = 16;
    final int G_2 = 17;
    final int G_3 = 18;
    final int G_4 = 19;
    final int G_5 = 20;
    final int G_6 = 21;
    final int G_7 = 22;
    final int G_8 = 23;
    final int G_9 = 24;
    final int D_1 = 25;
    final int D_2 = 26;
    final int D_3 = 27;
    final int D_4 = 28;
    final int D_5 = 29;
    final int D_6 = 30;
    final int D_7 = 31;
    final int H_1 = 32;
    final int H_2 = 33;
    final int H_3 = 34;
    final int H_4 = 35;
    final int H_5 = 36;
    final int E_1 = 37;

    Spinner mSpinnerType;

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

        String[] arrayList = {
                "(1) 회원정보 조회",
                "(2) 회원정보 수정",
                "(3) 회원정보 검증",
                "(4) 회원 비밀번호 수정",
                "(5) 인증 요청",
                "(6) 회원탈퇴",
                "(1) (마스터) 게스트 멤버추가",
                "(2) (마스터) 게스트 초대이력 조회",
                "(3) (마스터) 게스트 초대이력 삭제",
                "(4) (마스터) 게스트 멤버삭제",
                "(5) (마스터) 게스트 멤버 목록 조회",
                "(6) (마스터) 마스터에서 탈퇴",
                "(7) (게스트) 초대 이력 목록 조회",
                "(8) (게스트) 초대 승락/거절",
                "(9) (게스트) 마스터 정보 조회",
                "(10) (게스트) 멤버탈퇴",
                "(1) 디바이스 그룹 등록",
                "(2) 디바이스 그룹 조회",
                "(3) 디바이스 그룹 수정",
                "(4) 디바이스 그룹 삭제",
                "(5) 디바이스 그룹 목록 조회",
                "(6) 디바이스 그룹 목록 순서 변경",
                "(7) 디바이스 그룹 목록 별 디바이스 목록",
                "(8) 디바이스 그룹에 디바이스 연결",
                "(9) 디바이스 그룹에 디바이스 삭제",
                "(1) 디바이스 매핑",
                "(2) 디바이스 상세정보 조회",
                "(3) 디바이스 상세정보 수정",
                "(4) 디바이스 삭제(디바이스 초기화)",
                "(5) 디바이스 디바이스 최신 펌웨어 정보 조회",
                "(6) 디바이스 최신 펌웨어 업데이트",
                "(7) 디바이스 전체 목록 조회",
                "(1) 위치 정보 등록",
                "(2) 위치 정보 조회",
                "(3) 위치 정보 수정",
                "(4) 위치 정보 삭제",
                "(5) 날씨 정보 조회",
                "(1) 데이터 암호화",
        };




        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,arrayList);
        mSpinnerType = findViewById(R.id.spinnerType);
        mSpinnerType.setAdapter(arrayAdapter);


        String msg = "";
        msg += "ID Token : "+ AppHelper.getCurrSession().getIdToken().getJWTToken() + "\n";
        msg += "AC Token : "+ AppHelper.getCurrSession().getAccessToken().getJWTToken() + "\n";
        msg += "UserName : "+ AppHelper.getCurrSession().getUsername() + "\n";
        msg += "RF Token : "+ AppHelper.getCurrSession().getRefreshToken().getToken() + "\n";
        ((TextView)findViewById(R.id.txtResult)).setText(msg);

        CommonUtils.ErrorLogOutput(TAG, AppHelper.getCurrSession().getIdToken().getJWTToken());
    }

    @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.btnSend:
                ((TextView)findViewById(R.id.txtResult)).setText("");
                try {
                    switch (mSpinnerType.getSelectedItemPosition()) {
                        case U_1:
                            HttpApi.getUserInfo(mCallback);
                            break;
                        case U_2:
                            HttpApi.changeUserInfo("","테스트","01030477403",false,false, "", mCallback);
                            break;
                        case U_3:
                            HttpApi.isValidateUserInfo("red0aqua@naver.com","일명","01030477403", mCallback);
                            break;
                        case U_4:
                            //liM81102!
                            HttpApi.changeUserPassword(AppHelper.getCurrSession().getUsername(),"AQICAHjbIZwaQRyoV4KR8B7jV1DXHoxakY1ucl7Keca1obZv+QGVpZa2yFdPAHSjdY64iSfiAAAAZzBlBgkqhkiG9w0BBwagWDBWAgEAMFEGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMv79gC22hObsD2YR8AgEQgCQyUMRtrG6Zosisxe35cTK8jMtUFV6asX0mt74UORWp+UivRBU=",mCallback);
                            break;
                        case U_5:
                            HttpApi.requestConfirmUser(true,true,"red0aqua@naver.com",mCallback);
                            break;
                        case U_6:
                            HttpApi.deleteUserInfo(AppHelper.getCurrSession().getUsername(),"liM811021",mCallback);
                            break;
                        case M_1:
                            HttpApi.inviteGuestForMaster(true,"common.gnst@gmail.com",mCallback);
                            break;
                        case M_2:
                            HttpApi.getHistoryForInviteGuest(mCallback);
                            break;
                        case M_3:
                            HttpApi.deleteHistoryForInviteGuest("39772b61-dc47-450a-9648-bae4d086bace",mCallback);
                            break;
                        case M_4:
                            //미진행 작업.
                            ((TextView)findViewById(R.id.txtResult)).setText("미진행 작업.");
                            //HttpApi.deleteGuest("",mCallback);
                            break;
                        case M_5:
                            HttpApi.getGuestList(mCallback);
                            break;
                        case M_6:
                            HttpApi.deleteMasterInfo(mCallback);
                            break;
                        case M_7:
                            HttpApi.getHistoryForInvite(mCallback);
                            break;
                        case M_8:
                            HttpApi.acceptToInvite("47aacad0-4ec2-4686-9ef9-be8d130bba24OK",true,mCallback);
                            break;
                        case M_9:
                            HttpApi.getMasterInfo(mCallback);
                        case M_10:
                            //미진행 작업.
                            ((TextView)findViewById(R.id.txtResult)).setText("미진행 작업.");
                            //HttpApi.deleteGuestInfo("",mCallback);
                            break;
                        case G_1:
                            //기능 구현 완료.
                            ((TextView)findViewById(R.id.txtResult)).setText("기능 구현 완료");
                            break;
                        case G_2:
                            //기본그룹
                            HttpApi.getDeviceGroup("d8fcf171-396f-45b2-a8d1-24cc5dfe4d0f", mCallback);
                            break;
                        case G_3:
                            HttpApi.modifyDeviceGroup("a0c46d4a-f2f5-4ab8-b79a-978c0bdd58e9","테스트9999",GROUP_IMG_09_STRING,GROUP_BACKGROUND_09_STRING,mCallback);
                            break;
                        case G_4:
                            //기능 구현 완료
                            ((TextView)findViewById(R.id.txtResult)).setText("기능 구현 완료");
                            break;
                        case G_5:
                            HttpApi.getDeviceGroupList(mCallback);
                            break;
                        case G_6:
                            //기능 구현 완료.
                            ((TextView)findViewById(R.id.txtResult)).setText("기능 구현 완료");
                            break;
                        case G_7:
                            //기본그룹
                            HttpApi.getDeviceListInDeviceGroup("d8fcf171-396f-45b2-a8d1-24cc5dfe4d0f",mCallback);
                            break;
                        case G_8:
                            HttpApi.connectDeviceInDeviceGroup("d8fcf171-396f-45b2-a8d1-24cc5dfe4d0f","a12020081800004303",mCallback);
                        break;
                        case G_9:
                            //미진행 작업.
                            ((TextView)findViewById(R.id.txtResult)).setText("미진행 작업.");
                            break;
                        case D_1:
                            //HttpApi.mappingDevice("a12020091710000015",mCallback);
                            HttpApi.mappingDevice("a12020081800004403",mCallback);
                            //HttpApi.mappingDevice("a12020081800004302","테스트조명09","icon_01","background_01",mCallback);
                            break;
                        case D_2:
                            HttpApi.getDeviceInfo("a12020081800004403",mCallback);
                            break;
                        case D_3:
                            HttpApi.modifyDeviceInfo("a12020081800004403","우리집조명13",mCallback);
                            break;
                        case D_4:
                            HttpApi.deleteDevice("a12020081800004403",mCallback);
                            break;
                        case D_5:
                            HttpApi.getFirmwareInfoAtDevice("a12020081800004403",mCallback);
                            break;
                        case D_6:
                            HttpApi.updateFirmwareInfoAtDevice("a12020081800004403",mCallback);
                            break;
                        case D_7:
                            HttpApi.getAllDevice(mCallback);
                            break;
                        case H_1:
                            HttpApi.registerLocationInfo("37.6642357913395","127.040679390304","서울","도봉구","방학1동",mCallback);
                            break;
                        case H_2:
                            HttpApi.getLocationInfo(mCallback);
                            break;
                        case H_3:
                            HttpApi.modifyLocationInfo("e46e4d34-16f5-46b2-9579-8a8948cedf03","37.6642357913395","127.040679390304","서울","도봉구","방학1동",mCallback);
                            break;
                        case H_4:
                            HttpApi.deleteLocationInfo("e46e4d34-16f5-46b2-9579-8a8948cedf03",mCallback);
                            break;
                        case H_5:
                            HttpApi.getWeatherInfo("e46e4d34-16f5-46b2-9579-8a8948cedf03",mCallback);
                            break;
                        case E_1:
                            HttpApi.encryptData("liM81102!",mCallback);
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    final String msg =  "HttpApi.TEST(Exception)\n" + e.toString();
                    ErrorLogOutput(TAG, msg);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ((TextView)findViewById(R.id.txtResult)).setText(msg);
                        }
                    });
                }
                break;
            case R.id.btnBack:
                onBackPressed();
                break;
        }
    }

    Callback mCallback = new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
            final String msg =  "HttpApi.TEST(onFailure)\n" + e.toString();
            ErrorLogOutput(TAG, msg);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ((TextView)findViewById(R.id.txtResult)).setText(msg);
                }
            });
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            String temp = "HttpApi.TEST(onResponse) Response code : " + response.code() + "\nresponse : " + response.toString()+"\n";
            ErrorLogOutput(TAG, "HttpApi.TEST(onResponse) Response code : " + response.code() + "\nresponse : " + response.toString());
            try {
                JSONObject json_data = new JSONObject(response.body().string());
                ErrorLogOutput(TAG, "HttpApi.TEST(onResponse) body : " + json_data.toString());
                temp += "HttpApi.TEST(onResponse) body : " + json_data.toString();
            } catch (JSONException e) {
                ErrorLogOutput(TAG, "HttpApi.TEST(onResponse) JSONException : " + e.toString());
                temp += "HttpApi.TEST(onResponse) JSONException : " + e.toString();
            }

            final String msg = temp;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ((TextView)findViewById(R.id.txtResult)).setText(msg);
                }
            });
        }
    };
}