package com.haussteuerung;

import static android.os.Build.VERSION.SDK_INT;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.firebase.messaging.FirebaseMessaging;
import com.google.gson.Gson;

import org.eclipse.paho.client.mqttv3.MqttException;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView tv_WM1;
    private TextView tv_WM2;
    private TextView tv_mqtt;
    private Button buttonAlarm;
    public static String ID = "";
    public static boolean pausedMainActivity = true;
    public static boolean alarmStatus = false, wm1Status = false, wm2Status = false;
    private Context mContext;
    Timer myTimer = new Timer();
    Gson gson = new Gson();
    String msg;

    @SuppressLint("HardwareIds")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mContext = this;

        pausedMainActivity = false;

        Log.d("MainActivityPause", "onCreate true");

        // Ändern der Statusbar-Farbe
        androidx.appcompat.app.ActionBar actionBar = getSupportActionBar();
        assert actionBar != null;
        actionBar.setBackgroundDrawable(AppCompatResources.getDrawable(getApplicationContext(), R.drawable.gradient_titlebar));

        setContentView(R.layout.activity_main);

        ID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        Log.d("ID", ID);

        int permissionState = ContextCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS);
        // If the permission is not granted, request it.
        if (permissionState == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.POST_NOTIFICATIONS}, 1);
        }

        // Abfrage am Gerät, ob Speicher verwendet werden darf
        if (SDK_INT >= Build.VERSION_CODES.R) {
            Log.d("Permission", "" + SDK_INT);
            if (!Environment.isExternalStorageManager()) {
                ActivityCompat.requestPermissions(this,
                        new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE,
                                android.Manifest.permission.MANAGE_EXTERNAL_STORAGE}, 1);//permission request code is just an int
                File file = new File(Environment.getExternalStorageDirectory().getPath() + "/Pictures/Haussteuerung/");
                if (!file.exists()) {
                    file.mkdir();
                }
            }
        } else {
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        }

        FirebaseMessaging.getInstance().subscribeToTopic("general");
        FirebaseMessaging.getInstance().subscribeToTopic(ID);

        // Connecten des Mqtt-Clients
        try {
            MqttClient.connect();
        } catch (Exception e) {
            Log.d("MQTT", "Verbindung fehlgeschlagen");
        }
        // Log.d("MQTT", String.valueOf(MqttClient.connSuccess));
        // if (!MqttClient.connSuccess) {
        //     MqttClient.connect();
        // }

        // Instanzieren der Buttons und TextViews
        ImageView imageViewHaus = findViewById(R.id.imageViewHaus);
        Button buttonHaus = findViewById(R.id.buttonHaus);
        Button buttonGlocke = findViewById(R.id.buttonGlocke);
        Button buttonLicht = findViewById(R.id.buttonLicht);
        Button buttonLog = findViewById(R.id.buttonLog);
        Button buttonLWP = findViewById(R.id.buttonLWP);
        Button buttonDoris = findViewById(R.id.buttonDoris);
        Button buttonDorisLicht = findViewById(R.id.buttonDorisLicht);
        buttonAlarm = findViewById(R.id.buttonAlarm);
        tv_WM1 = findViewById(R.id.textview_WM1);
        tv_WM2 = findViewById(R.id.textview_WM2);
        tv_mqtt = findViewById(R.id.textView_Mqtt);
        buttonHaus.setOnClickListener(this);
        buttonGlocke.setOnClickListener(this);
        buttonLicht.setOnClickListener(this);
        buttonLog.setOnClickListener(this);
        buttonLWP.setOnClickListener(this);
        buttonDoris.setOnClickListener(this);
        buttonDorisLicht.setOnClickListener(this);
        imageViewHaus.setOnClickListener(this);

        imageViewHaus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialogHaus();
            }
        });

        imageViewHaus.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                alertDialogVersion();
                return true;
            }
        });

        buttonAlarm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("Alarm", String.valueOf(alarmStatus));
                if (alarmStatus) {
                    // Alarm ein, also ausschalten
                    MqttClient.publish("cmnd/Haussteuerung/Alarm", "{\"DeviceID\":\"" + ID + "\",\"Name\":\"Alarm\",\"Zustand\":\"true\"}");
                } else {
                    // Alarm aus, also einschalten
                    alertDialogAlarm();
                }
            }
        });

        Intent i = getIntent();
        if (i.getExtras() != null) {
            if (i.getExtras() != null && i.hasExtra("Time")) {
                Log.d("GlockeZeit", i.getStringExtra("Time"));
            }
            if ((i.getExtras() != null) && (i.hasExtra("Time"))) {
                Intent iGlocke = new Intent(MainActivity.this, activityGlocke.class);
                iGlocke.putExtra("TimeFB", i.getStringExtra("Time"));
                Log.d("GlockeZeit", i.getStringExtra("Time"));
                startActivity(iGlocke);
            }
            if ((i.getExtras() != null) && (i.hasExtra("Sky"))) {
                Intent iSky = new Intent(MainActivity.this, activitySky.class);
                Log.d("Sky", i.getStringExtra("Sky"));
                startActivity(iSky);
            }
            if ((i.getExtras() != null) && (i.hasExtra("Other"))) {
                Log.d("Other", i.getStringExtra("Other"));
                alertDialogNotification(i.getStringExtra("Other"));
            }
        }

        Log.d("MainActivityPause", "false");
    }

    private void TimerMethod() {
        this.runOnUiThread(Timer_Tick);
    }

    private final Runnable Timer_Tick = new Runnable() {
        public void run() {
            if (MqttClient.client.isConnected()) {
                tv_mqtt.setTextColor(Color.parseColor("#64DD17"));
            } else {
                tv_mqtt.setTextColor(Color.RED);
            }

            if (alarmStatus) {
                buttonAlarm.setText(R.string.alarm_ein);
                buttonAlarm.setBackgroundResource(R.drawable.alarm_true);
            } else {
                buttonAlarm.setText(R.string.alarm_aus);
                buttonAlarm.setBackgroundResource(R.drawable.alarm_false);
            }

            if (wm1Status) {
                tv_WM1.setText(R.string.wm1_laeuft);
            } else {
                tv_WM1.setText(R.string.wm1_aus);
            }

            if (wm2Status) {
                tv_WM2.setText(R.string.wm2_laeuft);
            } else {
                tv_WM2.setText(R.string.wm2_aus);
            }

            Log.d("TimerMainActivity", "Running");
        }
    };

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.buttonLWP:
                Intent iLWP = new Intent(MainActivity.this, activityLWP.class);
                startActivity(iLWP);
                break;
            case R.id.buttonDoris:
                Intent iDoris = new Intent(MainActivity.this, activityDoris.class);
                startActivity(iDoris);
                break;
            case R.id.buttonDorisLicht:
                Intent iDorisLicht = new Intent(MainActivity.this, activityDorisLicht.class);
                startActivity(iDorisLicht);
                break;
            case R.id.buttonHaus:
                Intent intent = new Intent(MainActivity.this, activityHaus.class);
                startActivity(intent);
                break;
            case R.id.buttonGlocke:
                Intent iGlocke = new Intent(MainActivity.this, activityGlocke.class);
                startActivity(iGlocke);
                break;
            case R.id.buttonLicht:
                Intent iLicht = new Intent(MainActivity.this, activityLicht.class);
                startActivity(iLicht);
                break;
            case R.id.buttonLog:
                Intent iLog = new Intent(MainActivity.this, activityLog.class);
                startActivity(iLog);
                break;
        }
    }

    // Methode zum Öffnen des AlertDialogs beim Klick aufs Haus-Foto
    public void alertDialogHaus() {
        // Titlebar ändern
        TextView textView = new TextView(getApplicationContext());
        textView.setText(R.string.tor_steuerung);
        textView.setPadding(20, 30, 20, 30);
        textView.setTextSize(20F);
        textView.setBackgroundResource(R.drawable.gradient_titlebar);
        textView.setTextColor(Color.WHITE);

        // AlertDialog instanzieren
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
        final View customLayout = getLayoutInflater().inflate(R.layout.layout_haus, null);
        alertDialog.setView(customLayout);
        alertDialog.setCustomTitle(textView);

        AlertDialog alert = alertDialog.create();
        alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        Button buttonGarage, buttonSchiebetor;
        buttonGarage = customLayout.findViewById(R.id.buttonAlarmJa);
        buttonSchiebetor = customLayout.findViewById(R.id.buttonAlarmNein);

        buttonGarage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                msg = gson.toJson(new Licht(MainActivity.ID, "Garagentor", "Lamp12"));
                MqttClient.publish("cmnd/Haussteuerung/Licht", msg);
                alert.cancel();
            }
        });

        buttonSchiebetor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                msg = gson.toJson(new Licht(MainActivity.ID, "Schiebetor", "Lamp31"));
                MqttClient.publish("cmnd/Haussteuerung/Licht", msg);Toast.makeText(mContext, "Schiebetor außer Betrieb", Toast.LENGTH_LONG).show();
                alert.cancel();
            }
        });
        alert.show();
    }

    public void alertDialogAlarm() {
        // Titlebar ändern
        TextView textView = new TextView(getApplicationContext());
        textView.setText(R.string.alarm_steuerung);
        textView.setPadding(20, 30, 20, 30);
        textView.setTextSize(20F);
        textView.setBackgroundResource(R.drawable.gradient_titlebar);
        textView.setTextColor(Color.WHITE);

        // AlertDialog instanzieren
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
        final View customLayout = getLayoutInflater().inflate(R.layout.layout_alarm, null);
        alertDialog.setView(customLayout);
        alertDialog.setCustomTitle(textView);

        AlertDialog alert = alertDialog.create();
        alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        Button buttonAlarmJa, buttonAlarmNein;
        buttonAlarmJa = customLayout.findViewById(R.id.buttonAlarmJa);
        buttonAlarmNein = customLayout.findViewById(R.id.buttonAlarmNein);

        buttonAlarmJa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MqttClient.tv_Zustand1.equals("zu") &&
                        MqttClient.tv_Zustand2.equals("zu") &&
                        MqttClient.tv_Zustand3.equals("zu") &&
                        MqttClient.tv_Zustand4.equals("zu") &&
                        MqttClient.tv_Zustand5.equals("zu") &&
                        MqttClient.tv_Zustand6.equals("zu") &&
                        MqttClient.tv_Zustand7.equals("zu") &&
                        MqttClient.tv_Zustand9.equals("zu") &&
                        MqttClient.tv_Zustand10.equals("zu") &&
                        MqttClient.tv_Zustand11.equals("zu") &&
                        MqttClient.tv_Zustand12.equals("zu") &&
                        MqttClient.tv_Zustand13.equals("zu") &&
                        MqttClient.tv_Zustand14.equals("zu") //&&
                    //MqttClient.tv_Zustand15.equals("zu") &&
                    //MqttClient.tv_Zustand16.equals("zu") &&
                    //MqttClient.tv_Zustand17.equals("zu") &&
                    //MqttClient.tv_Zustand18.equals("zu")
                ) {
                    MqttClient.publish("cmnd/Haussteuerung/Alarm", "{\"DeviceID\":\"" + ID + "\",\"Name\":\"Alarm\",\"Zustand\":\"false\"}");
                    alert.cancel();
                } else {
                    Toast.makeText(mContext, "Bitte offene Fenster/Türen schließen!", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(MainActivity.this, activityHaus.class);
                    startActivity(intent);
                }
            }
        });

        buttonAlarmNein.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alert.cancel();
            }
        });
        alert.show();
    }

    public void alertDialogVersion() {
        // Titlebar ändern
        TextView textView = new TextView(getApplicationContext());
        textView.setText(R.string.version_ad);
        textView.setPadding(20, 30, 20, 30);
        textView.setTextSize(20F);
        textView.setBackgroundResource(R.drawable.gradient_titlebar);
        textView.setTextColor(Color.WHITE);

        // AlertDialog instanzieren
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
        final View customLayout = getLayoutInflater().inflate(R.layout.layout_version, null);
        alertDialog.setView(customLayout);
        alertDialog.setCustomTitle(textView);

        AlertDialog alert = alertDialog.create();
        alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        alert.show();
    }

    public void alertDialogNotification(String content) {
        // Titlebar ändern
        TextView textView = new TextView(getApplicationContext());
        String title = "Benachrichtigung";
        textView.setText(title);
        textView.setPadding(20, 30, 20, 30);
        textView.setTextSize(20F);
        textView.setBackgroundResource(R.drawable.gradient_titlebar);
        textView.setTextColor(Color.WHITE);

        // AlertDialog instanzieren
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
        final View customLayout = getLayoutInflater().inflate(R.layout.layout_adnotification, null);
        alertDialog.setView(customLayout);
        alertDialog.setCustomTitle(textView);

        AlertDialog alert = alertDialog.create();
        alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        TextView textView_adConent, textView_adTimer;
        textView_adConent = customLayout.findViewById(R.id.tv_adcontent);
        textView_adTimer = customLayout.findViewById(R.id.tv_adtimer);

        ProgressBar pg_adProgressBar;
        pg_adProgressBar = customLayout.findViewById(R.id.progressBar);

        textView_adConent.setText(content);

        new CountDownTimer(10000, 1000) {
            public void onTick(long millisUntilFinished) {
                long timeRemain = ((millisUntilFinished / 1000));
                pg_adProgressBar.setProgress((int) timeRemain);
                textView_adTimer.setText(String.valueOf(timeRemain));
            }

            public void onFinish() {
                alert.cancel();
            }
        }.start();

        alert.show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        pausedMainActivity = true;
        Log.d("MainActivityPause", "onPause true");
        // Log.d("1MQTT onPause", String.valueOf(MqttClient.connSuccess));
        myTimer.cancel();
        Log.d("TimerMainActivity", "Canceled");
    }

    @Override
    protected void onStop() {
        super.onStop();
        pausedMainActivity = true;
        Log.d("MainActivityPause", "onStop true");
        // Log.d("1MQTT onStop", String.valueOf(MqttClient.connSuccess));
        // myTimer.cancel();
        // Log.d("TimerMainActivity", "Canceled");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("MainActivityPause", "onStart true");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("MainActivityPause", "onRestart true");

    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("MainActivityPause", "onResume true");
        Log.d("1MQTT onResume", String.valueOf(MqttClient.client.isConnected()));

        pausedMainActivity = false;

        buttonAlarm.setBackgroundResource(R.drawable.gradient_pressed);

        myTimer = new Timer();
        myTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                TimerMethod();
            }

        }, 0, 1000);
        Log.d("TimerMainActivity", "Started");

        if (!MqttClient.client.isConnected()) {
            Log.d("1MQTT onResume", "Client connected: " + MqttClient.client.isConnected());
            try {
                MqttClient.client.reconnect();
                Log.d("1MQTT onResume", "Try to reconnect client");
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        pausedMainActivity = true;
        // myTimer.cancel();
        Log.d("MainActivityPause", "onDestroy true");
        MqttClient.disconnect();
        // Log.d("1MQTT onDestroy", String.valueOf(MqttClient.connSuccess));
        finishAffinity();
    }
}