package com.example.surveillanceapp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;



import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import static com.example.surveillanceapp.MainActivity.EXTRA_NAME;
import static com.example.surveillanceapp.MainActivity.EXTRA_PASSWORD;
import static com.example.surveillanceapp.MainActivity.EXTRA_SERVER;


public class ActivityTwo extends AppCompatActivity {

    // static String HOST="tcp://farmer.cloudmqtt.com:13237";
    // static String USER="cqeopqjb";
    //static String PASSWORD="0ZilzPcY0rxh";

    private LocalBroadcastManager localBroadcastManager;

    //TextView subText;

    ImageView image1;
    Bitmap ext_pic;
    Bitmap ext_pic2;
    String formattedDate;
    String listH;

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String topic = intent.getStringExtra("topic");
            byte[] bytes = intent.getByteArrayExtra("bytes");
            String message = intent.getStringExtra("message");

            TextView subText =  findViewById(R.id.subText);

            if (topic.contains("Motion/")) {
                subText.setText("Motion/" + message);

            } else if (topic.contains("Detection/")) {
                subText.setText("Detection/" + message);
            } else if (topic.contains("Unknown/")) {
                subText.setText(message);
            }
            else if (topic.contains("Info/")) {
                subText.setText(message);
            } else if (topic.contains("Photo/")) {
                InputStream input = new ByteArrayInputStream(bytes);
                ext_pic = BitmapFactory.decodeStream(input);
                image1.setImageBitmap(ext_pic);

                // byte[] base64Decoded = org.apache.commons.codec.binary.Hex.decodeHex(imageString.toCharArray());
                System.out.println("Message:\n");
//                System.out.println(src);
                System.out.println("Pic:\n");
                // System.out.println(ext_pic);

            }
        }
    };


    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
                .setTitle("Disconnect")
                .setMessage("This action will disconnect you. Do you want to precede?")
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface arg0, int arg1) {
                        setResult(RESULT_OK, new Intent().putExtra("Disconnect", true));
                        ((CustomApplication)getApplicationContext()).getConnectionHandler().disconnectClient();
                        finish();
                    }

                }).create().show();
    }


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

        LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter("ListOfMessages"));

        CustomApplication appState = ((CustomApplication)getApplicationContext());// you can use getApplication() as well in the activity
        appState.getConnectionHandler().connectClient(getIntent());

        image1 = (ImageView) findViewById(R.id.imagePhoto);

        Button btPhoto = findViewById(R.id.btPhoto);

        btPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String topic = "Rpi/";
                String message = "pic";

                ((CustomApplication)getApplicationContext()).getConnectionHandler().sendMessage(topic, message);
            }
        });


        Button btMail = findViewById(R.id.btMail);

        btMail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String topic = "Rpi/Mail";
                String message = "mail";

                ((CustomApplication)getApplicationContext()).getConnectionHandler().sendMessage(topic, message);
            }
        });

        Button btSave = findViewById(R.id.btSave);

        btSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageDownload();
            }
        });

        Button btSettings = findViewById(R.id.btSettings);

        btSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openActivitySettings();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_activity_two, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()) {
            case R.id.item4:
                Toast.makeText(this, "Set up your schedule", Toast.LENGTH_SHORT).show();
                openActivityCalendar();
                return true;
            case R.id.item3:
                Toast.makeText(this, "Message history", Toast.LENGTH_SHORT).show();
                openActivityHistory();
                return true;
            case R.id.item5:
                Toast.makeText(this, "PIN code", Toast.LENGTH_SHORT).show();
                openActivityPIN();
                return true;
            case R.id.subitem1:
                Toast.makeText(this, "Detection is ON", Toast.LENGTH_SHORT).show();
                String message = "ON";
                byte[] encodedPayload = new byte[0];
                try {
                    ((CustomApplication) getApplicationContext()).getConnectionHandler().client.publish("Rpi/", message.getBytes(), 0, false);
                } catch (MqttException e) {
                    e.printStackTrace();
                }
                return true;
            case R.id.subitem2:
                Toast.makeText(this, "Detection is OFF", Toast.LENGTH_SHORT).show();
                String messageOFF = "OFF";
                try {
                    ((CustomApplication) getApplicationContext()).getConnectionHandler().client.publish("Rpi/", messageOFF.getBytes(), 0, false);
                } catch (MqttException e) {
                    e.printStackTrace();
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);

        }
    }


    public void imageDownload(){
        Toast.makeText(this, "Image was downloaded", Toast.LENGTH_SHORT).show();
        ActivityCompat.requestPermissions(ActivityTwo.this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        Calendar c = Calendar.getInstance();
        System.out.println("Current time => "+c.getTime());
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        formattedDate = df.format(c.getTime());
        MediaStore.Images.Media.insertImage(getContentResolver(), ext_pic2, "ImagePreview "+formattedDate , "Image preview");
    }

    public  void openActivityCalendar(){

        Intent intent = new Intent(this, ActivityCalendar.class);
        startActivity(intent);
    }

    public  void openActivityHistory(){

        Intent intent = new Intent(this, ActivityHistory.class);
        startActivity(intent);
    }

    public  void openActivitySettings(){

        Intent intentPhoto = new Intent(this, ActivitySettings.class);
        startActivity(intentPhoto);
    }

    public  void openActivityPIN(){

        Intent intent = new Intent(this, ActivityPIN.class);
        startActivity(intent);
    }

}
