package com.app.androidkt.mqttdemo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.MqttException;

//publish message
//pahoMqttClient.publishMessage(client, msg, 1, Constants.PUBLISH_TOPIC);
//subscribe message
//pahoMqttClient.subscribe(client, topic, 1);
//unsubscribe message
//pahoMqttClient.unSubscribe(client, topic);
public class MainActivity extends Activity {

    private MqttAndroidClient client;
    private String TAG = "MainActivity";
    private PahoMqttClient pahoMqttClient;

    private TextView TempTxt,IdTxt,HumiTxt,UpdateTxt;
    private ImageView TempImg;
    private EditText IDEdit;
    private Button UpdateBut;

    private String serialID ="FFFFFF";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        findViews();
        Initianl_All();
        Set_Listener();


    }
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        try {

            LocalBroadcastManager.getInstance(this).unregisterReceiver(MQTTStatusChangeReceiver);
        } catch (Exception ignore) {
            Log.e(TAG, ignore.toString());
        }
        Intent intent = new Intent(MainActivity.this, MqttMessageService.class);
        stopService(intent);
    }
    private void findViews(){

        TempTxt = (TextView) findViewById(R.id.temptxt);
        IdTxt = (TextView) findViewById(R.id.idtxt);
        UpdateTxt = (TextView) findViewById(R.id.updatetxt);
        HumiTxt = (TextView) findViewById(R.id.humitxt);
        TempImg = (ImageView) findViewById(R.id.tempicon);
        IDEdit = (EditText) findViewById(R.id.enterid);
        UpdateBut = (Button) findViewById(R.id.updatebut);

    }
    private void Initianl_All(){

        Read_Set_XML(this);
        Intent intent = new Intent(MainActivity.this, MqttMessageService.class);
        startService(intent);



        LocalBroadcastManager.getInstance(this).registerReceiver(MQTTStatusChangeReceiver, makeMQTTUpdateIntentFilter());
        IdTxt.setText("ID:"+serialID);

        pahoMqttClient = new PahoMqttClient();
        client = pahoMqttClient.getMqttClient(getApplicationContext(), Constants.MQTT_BROKER_URL, Constants.CLIENT_ID);
    }
    private void Set_Listener(){

        UpdateBut.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                String temp = IDEdit.getText().toString();
                if(temp.length() != 6){
                    Toast.makeText(MainActivity.this,"ID format incorret!",Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MainActivity.this,"Update sucessful!",Toast.LENGTH_SHORT).show();
                    TempTxt.setText("Temperature: Waitting");
                    HumiTxt.setText("Humidity: Waitting");
                    String Canceltopic = "";
                    Canceltopic = Constants.SUBSCRIBE_TOPIC+ serialID+Constants.SUBSCRIBE_Sub_Inid;
                    try {
                        pahoMqttClient.unSubscribe(client, Canceltopic);
                    }catch (MqttException e) {
                        e.printStackTrace();
                    }
                    
                    Canceltopic = Constants.SUBSCRIBE_TOPIC32+ serialID+Constants.SUBSCRIBE_Sub_Inid;
                    try {
                        pahoMqttClient.unSubscribe(client, Canceltopic);
                    }catch (MqttException e) {
                        e.printStackTrace();
                    }  

                    serialID = "";
                    for(int i=0;i<temp.length();i++) {
                        serialID = serialID+ String.valueOf(temp.charAt(i)).toUpperCase();
                    }
                    IdTxt.setText("ID:"+serialID);
                    Save_Set_XML(MainActivity.this);
                    String Outtopic = "";
                    Outtopic = Constants.SUBSCRIBE_TOPIC+ serialID+Constants.SUBSCRIBE_Sub_Inid;
                    Log.d(TAG,"Outtopic="+Outtopic);
                    //resetart the app


                    try{
                        pahoMqttClient.subscribe(client, Outtopic, 1);
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                }

            }});


    }
    private final BroadcastReceiver MQTTStatusChangeReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals(Constants.MQTT_CONNECTION)) {
                UpdateTxt.setText("Connected:"+Calendar.getInstance().getTime());

                try{
                    String Outtopic = "";
                    Outtopic = Constants.SUBSCRIBE_TOPIC+ serialID+Constants.SUBSCRIBE_Sub_Inid;
                    pahoMqttClient.subscribe(client, Outtopic, 1);
                } catch (MqttException e) {
                    if(e != null)
                        e.printStackTrace();
                    else
                        Log.e(TAG, "Sub request exception");
                }
                try{
                    String Outtopic = "";
                    Outtopic = Constants.SUBSCRIBE_TOPIC32+ serialID+Constants.SUBSCRIBE_Sub_Inid;
                    pahoMqttClient.subscribe(client, Outtopic, 1);
                } catch (MqttException e) {
                    if(e != null)
                        e.printStackTrace();
                    else
                        Log.e(TAG, "Sub request exception");
                }


            }


            if (action.equals(Constants.MQTT_RECEIVED)) {
                final String temp_str= intent.getStringExtra(Constants.MQTT_BROADCAST);
                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
                String strDate = "Messages updated : " + mdformat.format(calendar.getTime());
                UpdateTxt.setText(strDate);
                if(temp_str.length() == 17) {
                    if(temp_str.charAt(0) == 'T' && temp_str.charAt(1) == 'e'){
                        if(temp_str.charAt(5) == '0')
                            TempTxt.setText("Temperature: "+temp_str.charAt(6)+temp_str.charAt(7)+"°C ");
                        else
                            TempTxt.setText("Temperature: "+temp_str.charAt(5)+temp_str.charAt(6)+temp_str.charAt(7)+"°C ");
                    }
                    if(temp_str.charAt(9) == 'H' && temp_str.charAt(10) == 'u'){
                        if(temp_str.charAt(14) == '0')
                            HumiTxt.setText("Humidity: "+temp_str.charAt(15)+temp_str.charAt(16)+"%");
                        else
                            HumiTxt.setText("Humidity: "+temp_str.charAt(14)+temp_str.charAt(15)+temp_str.charAt(16)+"%");
                    }

                }
            }





        }
    };
    private static IntentFilter makeMQTTUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.MQTT_CONNECTION);
        intentFilter.addAction(Constants.MQTT_RECEIVED);
        return intentFilter;
    }
    /************************************************
     * Feature: Save Key disable xml
     * input:none
     * output:none
     ************************************************/
    private void Save_Set_XML(Context context) {
        SharedPreferences settings = context.getSharedPreferences("set_buff", 0);
        settings.edit()
        .putString("serialID", serialID)
        .commit();
    }
    /*****************************************/
    /**read the keydisabled
     ******************************************/
    private void Read_Set_XML(Context context) {
        SharedPreferences settings = context.getSharedPreferences("set_buff", 0);
        String tempID = settings.getString("serialID", "FFFFFF");


        serialID = "";
        for(int i=0;i<tempID.length();i++) {
            serialID = serialID+ String.valueOf(tempID.charAt(i)).toUpperCase();
        }
    }

}
