package com.haussteuerung;

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.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.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
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.lifecycle.ProcessLifecycleOwner;

import com.google.firebase.messaging.FirebaseMessaging;
import com.google.gson.Gson;
import com.haussteuerung.helper.Licht;

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

import java.util.Objects;
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 alarmStatus = false, wm1Status = false, wm2Status = false;
    private Context mContext;
    Timer myTimer = new Timer();
    Gson gson = new Gson();
    String msg;

    @RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
    @SuppressLint("HardwareIds")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ProcessLifecycleOwner.get().getLifecycle().addObserver(new AppLifecycleTracker());

        mContext = this;

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

        setContentView(R.layout.activity_main);

        String androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        ID = "haussteuerung-android-" + Build.MODEL + "-" + androidId;
        Log.d("ID", ID);

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

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

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

        // 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(view -> alertDialogHaus());

        imageViewHaus.setOnLongClickListener(view -> {
            alertDialogVersion();
            return true;
        });

        buttonAlarm.setOnClickListener(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"))) {
                Intent iGlocke = new Intent(MainActivity.this, activityGlocke.class);
                iGlocke.putExtra("TimeFB", i.getStringExtra("Time"));
                Log.d("GlockeZeit", Objects.requireNonNull(i.getStringExtra("Time")));
                startActivity(iGlocke);
            }
            if ((i.getExtras() != null) && (i.hasExtra("Other"))) {
                Log.d("Other", Objects.requireNonNull(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();
        Objects.requireNonNull(alert.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        Button buttonGarage, buttonSchiebetor;
        buttonGarage = customLayout.findViewById(R.id.buttonAlarmJa);
        buttonSchiebetor = customLayout.findViewById(R.id.buttonAlarmNein);

        buttonGarage.setOnClickListener(view -> {
            msg = gson.toJson(new Licht(MainActivity.ID, "Garagentor", "Lamp12"));
            MqttClient.publish("cmnd/Haussteuerung/Licht", msg);
            alert.cancel();
        });

        buttonSchiebetor.setOnClickListener(view -> {
            msg = gson.toJson(new Licht(MainActivity.ID, "Schiebetor", "Lamp31"));
            MqttClient.publish("cmnd/Haussteuerung/Licht", msg);
            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();
        Objects.requireNonNull(alert.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        Button buttonAlarmJa, buttonAlarmNein;
        buttonAlarmJa = customLayout.findViewById(R.id.buttonAlarmJa);
        buttonAlarmNein = customLayout.findViewById(R.id.buttonAlarmNein);

        buttonAlarmJa.setOnClickListener(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.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(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();
        Objects.requireNonNull(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();
        Objects.requireNonNull(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();
        myTimer.cancel();
        Log.d("TimerMainActivity", "Canceled");
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onRestart() {
        super.onRestart();

    }

    @Override
    protected void onResume() {
        super.onResume();

        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) {
                Log.d("1MQTT onResume", "Try to reconnect client failed: " + e);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MqttClient.disconnect();
        finishAffinity();
    }
}