package kr.co.icontrols.iotplatform;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.CognitoCachingCredentialsProvider;
import com.amazonaws.internal.StaticCredentialsProvider;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttClientStatusCallback;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttManager;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttNewMessageCallback;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttQos;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;

import static kr.co.icontrols.iotplatform.utils.CommonUtils.DebugLogOutput;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.ErrorLogOutput;

public class TestIotMqttActivity extends AppCompatActivity implements View.OnClickListener {

    private String TAG = "TestIotMqttActivity";
    private String COGNITO_POOL_ID = "ap-northeast-2:0e617292-1b9c-4208-b64b-b2d03729b25b";
    //"a12020091710000015"
    private String TOPIC1 = "$aws/things/a12020091710000015/shadow/get"; //publish
    private String TOPIC2 = "$aws/things/a12020091710000015/shadow/get/accepted";
    private String TOPIC3 = "$aws/things/a12020091710000015/shadow/get/rejected";
    private String TOPIC4 = "$aws/things/a12020091710000015/shadow/update"; //publish
    private String TOPIC5 = "$aws/things/a12020091710000015/shadow/update/accepted";
    private String TOPIC6 = "$aws/things/a12020091710000015/shadow/update/delta";
    private String ACCOUNT_END_POINT_PREFIX = "a139udwm0q3u52-ats";
    private String END_POINT = "wss://a139udwm0q3u52-ats.iot.ap-northeast-2.amazonaws.com";
    private String ACCESS_KEY = "AKIAUSTWEOGGE4XFHBWL";
    private String SECRET_KEY = "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";

    private EditText txtInput;
    private TextView txtResult;

    private AWSCredentials awsCredentials;
    private static AWSCredentialsProvider credentialsProvider;
    //private static CognitoCachingCredentialsProvider credentialsProvider;
    private static AWSIotMqttManager mqttManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_iot_mqtt);

        txtInput = findViewById(R.id.txtInput);
        txtResult = findViewById(R.id.txtResult);

        txtResult.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                txtResult.setText("");
                return false;
            }
        });

        /*
        //Amazon Cognito 인증 공급자를 초기화합니다
        credentialsProvider = new CognitoCachingCredentialsProvider(
                getApplicationContext(),
                COGNITO_POOL_ID, // 자격 증명 풀 ID
                Regions.AP_NORTHEAST_2 // 리전
        );
        */

        //Amazon Cognito 인증 공급자를 초기화합니다
        credentialsProvider = new StaticCredentialsProvider(
                new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY));

        //intialize unnqique clientid as client to iot aws
        Long tsLong = System.currentTimeMillis()/1000;
        String clientId = tsLong.toString();

        mqttManager = new AWSIotMqttManager(
                clientId/*"android_iot_app_test_mqtt"*/,
                Region.getRegion(Regions.AP_NORTHEAST_2),
                ACCOUNT_END_POINT_PREFIX
        );

        new Thread(new Runnable() {
            @Override
            public void run() {
                awsCredentials = credentialsProvider.getCredentials();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        findViewById(R.id.btnConnect).setEnabled(true);
                        Toast.makeText(TestIotMqttActivity.this, "credentials ok?", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }).start();
    }

    @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.btnBack:
                onBackPressed();
                break;
            case R.id.btnSend:
                try {
                    if(txtInput.getText().toString().isEmpty()) {
                        mqttManager.publishString(/*"{\n" +
                            "    \"state\": {\n" +
                            "        \"desired\" : {\n" +
                            "            \"power\" : 1,\n" +
                            "            \"dimm\" : 20\n" +
                            "        }\n" +
                            "    }\n" +
                            "}"+*/txtInput.getText().toString(), TOPIC1, AWSIotMqttQos.QOS0);
                    } else {
                        mqttManager.publishString("{\n" +
                            "    \"state\": {\n" +
                            "        \"desired\" : {\n" +
                            "            \"power\" : 1,\n" +
                            "            \"dimm\" : "+txtInput.getText().toString()+"\n" +
                            "        }\n" +
                            "    }\n" +
                            "}", TOPIC4, AWSIotMqttQos.QOS0);
                    }

                } catch (Exception e) {
                    ErrorLogOutput(TAG, "Publish error. / " + e);
                }
                txtInput.setText("");
                break;
            case R.id.btnConnect:
                if(credentialsProvider != null) {
                    // connect to AWS IoT using credentials provider
                    mqttManager.connect(credentialsProvider, new AWSIotMqttClientStatusCallback() {
                        @Override
                        public void onStatusChanged(AWSIotMqttClientStatus status, Throwable throwable) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (status == AWSIotMqttClientStatus.Connecting) {
                                        txtResult.setText("Connecting..."+"\n"+txtResult.getText());
                                    } else if (status == AWSIotMqttClientStatus.Connected) {
                                        txtResult.setText("Connected"+"\n"+txtResult.getText());

                                        // subscribe to MQTT topic
                                        mqttManager.subscribeToTopic(TOPIC2, AWSIotMqttQos.QOS0, new AWSIotMqttNewMessageCallback() {
                                            @Override
                                            public void onMessageArrived(String topic, byte[] data) {
                                                DebugLogOutput(TAG, "Client persistent-client-id-1 received a message on topic:" + topic);
                                                DebugLogOutput(TAG, "onMessageArrived / "+TOPIC5+"\n"+new String(data));
                                                txtResult.setText(new String(data) + "\n" + txtResult.getText());
                                            }
                                        });

                                        mqttManager.subscribeToTopic(TOPIC3, AWSIotMqttQos.QOS0, new AWSIotMqttNewMessageCallback() {
                                            @Override
                                            public void onMessageArrived(String topic, byte[] data) {
                                                DebugLogOutput(TAG, "Client persistent-client-id-1 received a message on topic:" + topic);
                                                DebugLogOutput(TAG, "onMessageArrived / "+TOPIC6+"\n"+new String(data));
                                                txtResult.setText(new String(data) + "\n" + txtResult.getText());
                                            }
                                        });

                                        mqttManager.subscribeToTopic(TOPIC5, AWSIotMqttQos.QOS0, new AWSIotMqttNewMessageCallback() {
                                            @Override
                                            public void onMessageArrived(String topic, byte[] data) {
                                                DebugLogOutput(TAG, "Client persistent-client-id-1 received a message on topic:" + topic);
                                                DebugLogOutput(TAG, "onMessageArrived / "+TOPIC5+"\n"+new String(data));
                                                txtResult.setText("" + new String(data) + "\n" + txtResult.getText());
                                            }
                                        });

                                        mqttManager.subscribeToTopic(TOPIC6, AWSIotMqttQos.QOS0, new AWSIotMqttNewMessageCallback() {
                                            @Override
                                            public void onMessageArrived(String topic, byte[] data) {
                                                DebugLogOutput(TAG, "Client persistent-client-id-1 received a message on topic:" + topic);
                                                DebugLogOutput(TAG, "onMessageArrived / "+TOPIC6+"\n"+new String(data));
                                                txtResult.setText(new String(data) + "\n" + txtResult.getText());
                                            }
                                        });

                                    } else if (status == AWSIotMqttClientStatus.Reconnecting) {
                                        if (throwable != null) {
                                            DebugLogOutput(TAG, "Connection error. / " + throwable);
                                        }
                                        txtResult.setText("Reconnecting"+"\n"+txtResult.getText());
                                    } else if (status == AWSIotMqttClientStatus.ConnectionLost) {
                                        if (throwable != null) {
                                            DebugLogOutput(TAG, "Connection error. / " + throwable);
                                            throwable.printStackTrace();
                                        }
                                        txtResult.setText("Disconnected"+"\n"+txtResult.getText());
                                    } else {
                                        txtResult.setText("Disconnected"+"\n"+txtResult.getText());
                                    }
                                }
                            });
                        }
                    });
                } else {
                    Toast.makeText(TestIotMqttActivity.this, "credentials is null", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}