package com.haussteuerung;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

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

import com.google.firebase.encoders.json.BuildConfig;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class FileDownload extends AppCompatActivity {

    static String f1 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Haussteuerung_Flo.apk";
    static File apk = new File(f1);
    static boolean downloadFinished = false;
    TextView txt_status;
    Button button_Install;

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

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

        button_Install = findViewById(R.id.button_Install);
        TextView txt_changelog = findViewById(R.id.txt_changelog);
        txt_status = findViewById(R.id.txt_status);
        downloadFile();

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

    Uri uriFromFile(Context context, File file) {
        return FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
    }

    void installAPK() {
        if (apk.exists()) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uriFromFile(getApplicationContext(), apk), "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            try {
                getApplicationContext().startActivity(intent);
            } catch (ActivityNotFoundException e) {
                e.printStackTrace();
                Log.e("TAG", "Error in opening the file!");
            }
        } else {
            Toast.makeText(getApplicationContext(), "installing", Toast.LENGTH_LONG).show();
        }
    }


    public void downloadFile() {
        if (apk.exists()) {
            apk.delete();
        }

        String url = "http://www.klebl.info/download/Haussteuerung_Flo.apk";
        Log.d("Foto", url);

        Thread gfgThread = new Thread(() -> {
            try {
                InputStream in = null;
                try {
                    in = new URL(url).openStream();
                    String text = "Verbindung zum Server erfolgreich. Download wird durchgeführt.";
                    txt_status.setText(text);
                    Log.d("APK", "Verbindung zum Server erfolgreich. Download wird durchgeführt.");
                } catch (IOException e) {
                    String text = "Verbindungsfehler.";
                    txt_status.setText(text);
                    Log.d("APK", "Verbindungsfehler.");
                }
                try {
                    Files.copy(in, Paths.get(f1), StandardCopyOption.REPLACE_EXISTING);
                    downloadFinished = true;
                    button_Install.setBackgroundResource(R.drawable.alarm_false);
                    String text = "Download erfolgreich. Zum Installieren drücken!";
                    txt_status.setText(text);
                    Log.d("APK", "Download und Speichern erfolgreich.");
                } catch (IOException e) {
                    String text = "Download fehlgeschlagen.";
                    txt_status.setText(text);
                    Log.d("APK", "Download fehlgeschlagen.");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        gfgThread.start();
    }
}