/* Copyright 2014-2023 askanimus@gmail.com */

/* This File is part of "Arbeitszeitkonto" (askanimus.arbeitszeiterfassung2).
 *
 * "Arbeitszeitkonto" (askanimus.arbeitszeiterfassung2) is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * "Arbeitszeitkonto" (askanimus.arbeitszeiterfassung2) is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with "Arbeitszeitkonto" (askanimus.arbeitszeiterfassung2).  If not, see <http://www.gnu.org/licenses/>.
 *
 * Diese Datei ist Teil von "Arbeitszeitkonto" (askanimus.arbeitszeiterfassung2).
 *
 * "Arbeitszeitkonto" (askanimus.arbeitszeiterfassung2) ist Freie Software: Sie können es unter den Bedingungen
 * der GNU General Public License, wie von der Free Software Foundation,
 * Version 3 der Lizenz oder (nach Ihrer Wahl) jeder neueren
 * veröffentlichten Version, weiter verteilen und/oder modifizieren.
 *
 * "Arbeitszeitkonto" (askanimus.arbeitszeiterfassung2) wird in der Hoffnung, dass es nützlich sein wird, aber
 * OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
 * Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
 * Siehe die GNU General Public License für weitere Details.
 *
 * Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
 * Programm erhalten haben. Wenn nicht, siehe <https://www.gnu.org/licenses/>.
 */
package askanimus.arbeitszeiterfassung2.export;

import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.PersistableBundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.OneShotPreDrawListener;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.preference.PreferenceManager;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;

import askanimus.arbeitszeiterfassung2.Datum;
import askanimus.arbeitszeiterfassung2.MainActivity;
import askanimus.arbeitszeiterfassung2.R;
import askanimus.arbeitszeiterfassung2.StorageHelper;
import askanimus.arbeitszeiterfassung2.arbeitsplatz.Arbeitsplatz;
import askanimus.arbeitszeiterfassung2.datenbank.DatenbankHelper;
import askanimus.arbeitszeiterfassung2.setup.ASettings;
import askanimus.arbeitszeiterfassung2.setup.ISettings;
import askanimus.arbeitszeiterfassung2.setup.LocaleHelper;

public class ExportActivity extends AppCompatActivity implements ISettings {
    private ViewPager2 mViewPager;
    private Toolbar mToolbar;
    private TabLayout mTabLayout;

    /*private Export_Fragment_Woche fWoche;
    private Export_Fragment_Monat fMonat;
    private Export_Fragment_Jahr fJahr;
    private Export_Fragment_Einsatzort fEort;
    private Export_Fragment_Zeitraum fZeitraum;*/

    int maxFragments = 5;
    private final IExport_Fragment[] exportFragmente = new IExport_Fragment[maxFragments];
    private StorageHelper mStorageHelper;

    private Datum exportDatum;

    private final Context mContext = this;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(
                PreferenceManager
                        .getDefaultSharedPreferences(getApplicationContext())
                        .getBoolean(ASettings.KEY_THEMA_DUNKEL, false) ?
                        R.style.MyFullscreenTheme :
                        R.style.MyFullscreenTheme_Light
        );
        setContentView(R.layout.activity_export);
        // Anzeigeelemente finden
        mToolbar = findViewById(R.id.E_toolbar);
        mViewPager = findViewById(R.id.E_container);
        mTabLayout = findViewById(R.id.E_tabs);
        if(getSupportActionBar() == null)
            setSupportActionBar(mToolbar);

        getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                BackPressed();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        requestCode = requestCode & 0x0000ffff;

        if (data != null && resultCode == RESULT_OK && requestCode == REQ_FOLDER_PICKER_WRITE_EXPORT) {
            Uri treeUri = data.getData();
            if (treeUri != null) {
                getContentResolver()
                        .takePersistableUriPermission(
                                treeUri,
                                Intent.FLAG_GRANT_READ_URI_PERMISSION
                                                | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                        );
                mStorageHelper.setPfad(data.getDataString());
            }
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        ASettings.init(mContext, this::resume);
    }

    private void resume() {
        // alten Zustand der App wieder anzeigen
        SharedPreferences.Editor mEdit = ASettings.mPreferenzen.edit();
        mEdit.putBoolean(ISettings.KEY_RESUME_VIEW, true).apply();

        mToolbar.setTitle(ASettings.res.getString(R.string.title_activity_export));

        // den Exportpfad überprüfen
        if (mStorageHelper == null) {
            String ExportPfad = Environment.getExternalStorageDirectory().getAbsolutePath();
            /*if (ExportPfad != null) {*/
                ExportPfad += File.separator + ASettings.res.getString(R.string.app_verzeichnis);
                ExportPfad = ASettings.mPreferenzen.getString(ASettings.KEY_DATEN_DIR, ExportPfad);
                mStorageHelper = new StorageHelper(
                        this,
                        ExportPfad,
                        DatenbankHelper.DB_F_DATEN_DIR,
                        ASettings.KEY_DATEN_DIR,
                        true,
                        REQ_FOLDER_PICKER_WRITE_EXPORT/*,
                        null*/
                );
           /* }*/
        }

        exportDatum = new Datum(
                ASettings.mPreferenzen.getLong(
                        ISettings.KEY_ANZEIGE_DATUM, ASettings.aktDatum.getTimeInMillis()),
                ASettings.aktJob.getWochenbeginn());

        SectionsPagerAdapter mSectionsPagerAdapter =
                new SectionsPagerAdapter(getSupportFragmentManager(), getLifecycle());

        // Viewpager und Tabstrip erstellen
        mViewPager.setAdapter(mSectionsPagerAdapter);
        String[] tabTitel = ASettings.res.getStringArray(R.array.export_titel);
        TabLayoutMediator mTabMediator = new TabLayoutMediator(
                mTabLayout,
                mViewPager,
                true,
                true,
                (tab, position) -> tab.setText(tabTitel[position]));
        mTabMediator.attach();
        mTabLayout.setSelectedTabIndicatorColor(ASettings.aktJob.getFarbe());
        Intent intent = getIntent();
        OneShotPreDrawListener.add(
                mViewPager, () -> mViewPager.setCurrentItem(
                        intent.getIntExtra(ISettings.KEY_ANZEIGE_VIEW, 0),
                        true)
        );
        //mViewPager.setCurrentItem(intent.getIntExtra(ISetup.KEY_ANZEIGE_VIEW, 0));
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(LocaleHelper.onAttach(base));
    }

    /*
     * Rückmeldung vom Rechtemanagent nach Rechteeinforderung
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2) {
            requestCode = requestCode & 0x0000ffff;

            if (requestCode == REQ_DEMAND_WRITE) {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_DENIED) {
                    // Recht verweigert die Exportaktivity wird geschlossen
                    Toast.makeText(
                            ExportActivity.this,
                            getString(R.string.err_keine_berechtigung),
                            Toast.LENGTH_LONG
                    ).show();
                    finish();
                }
            }
        }
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Intent intent = getIntent();
        intent.putExtra(
                ISettings.KEY_ANZEIGE_VIEW,
                mViewPager != null ? mViewPager.getCurrentItem() : 0);
    }

    private void BackPressed() {
        // alten Zustand der App wieder anzeigen
        SharedPreferences.Editor mEdit = ASettings.mPreferenzen.edit();
        mEdit.putBoolean(ISettings.KEY_RESUME_VIEW, true).apply();

        Intent mMainIntent = new Intent();
        mMainIntent.setClass(this, MainActivity.class);
        mMainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        finish();
        startActivity(mMainIntent);
    }

    @Override
    protected void onDestroy() {
        if (isChangingConfigurations()) {
            Intent mExportIntent = new Intent();
            mExportIntent.setClass(this, ExportActivity.class);
            mExportIntent.putExtra(ISettings.KEY_JOBID, ASettings.aktJob.getId());
            if (mViewPager != null) {
                mExportIntent.putExtra(
                        ISettings.KEY_ANZEIGE_VIEW,
                        mViewPager.getCurrentItem()
                );
            }

            startActivity(mExportIntent);
        }
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Ein Menü mit Exportoptionen einfügen
        getMenuInflater().inflate(R.menu.menu_export, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        int oSeite = mViewPager.getCurrentItem();

        if(oSeite >= 0 && oSeite < maxFragments) {
            if (exportFragmente[oSeite] != null) {
                int aktion;
                if (id == R.id.export_action_save) {
                    aktion = IExport_Basis.ACTION_SAVE;
                } else if (id == R.id.export_action_send) {
                    aktion = IExport_Basis.ACTION_SEND;
                } else if (id == R.id.export_action_druck) {
                    aktion = IExport_Basis.ACTION_SHARE;
                } else {
                    return super.onOptionsItemSelected(item);
                }
                exportFragmente[oSeite].action(
                        aktion,
                        ASettings.aktJob,
                        mStorageHelper);
                return true;
            }
        }
        /*if (id == R.id.export_action_save) {
                switch (oSeite) {
                    case 0:
                        if (fWoche != null)
                            fWoche.action(
                                    IExport_Basis.ACTION_SAVE,
                                    ASettings.aktJob,
                                    mStorageHelper);
                        break;
                    case 1:
                        if (fMonat != null)
                            fMonat.action(
                                    IExport_Basis.ACTION_SAVE,
                                    ASettings.aktJob,
                                    mStorageHelper);
                        break;
                    case 2:
                        if (fJahr != null)
                            fJahr.action(
                                    IExport_Basis.ACTION_SAVE,
                                    ASettings.aktJob,
                                    mStorageHelper);
                        break;
                    case 3:
                        if (fZeitraum != null)
                            fZeitraum.action(
                                    IExport_Basis.ACTION_SAVE,
                                    ASettings.aktJob,
                                    mStorageHelper);
                        break;
                    case 4:
                        if (fEort != null)
                            fEort.action(
                                    IExport_Basis.ACTION_SAVE,
                                    ASettings.aktJob,
                                    mStorageHelper);
                        break;

                }
                return true;
            } else if (id == R.id.export_action_send) {
                switch (oSeite) {
                    case 0:
                        if (fWoche != null)
                            fWoche.action(IExport_Basis.ACTION_SEND,
                                    ASettings.aktJob, mStorageHelper);
                        break;
                    case 1:
                        if (fMonat != null)
                            fMonat.action(IExport_Basis.ACTION_SEND,
                                    ASettings.aktJob, mStorageHelper);
                        break;
                    case 2:
                        if (fJahr != null)
                            fJahr.action(IExport_Basis.ACTION_SEND,
                                    ASettings.aktJob, mStorageHelper);
                        break;
                    case 3:
                        if (fZeitraum != null)
                            fZeitraum.action(IExport_Basis.ACTION_SEND,
                                    ASettings.aktJob, mStorageHelper);
                        break;
                    case 4:
                        if (fEort != null)
                            fEort.action(IExport_Basis.ACTION_SEND,
                                    ASettings.aktJob, mStorageHelper);
                        break;
                }

                return true;
            } else if (id == R.id.export_action_druck) {
                switch (oSeite) {
                    case 0:
                        if (fWoche != null)
                            fWoche.action(IExport_Basis.ACTION_SHARE,
                                    ASettings.aktJob, mStorageHelper);
                        break;
                    case 1:
                        if (fMonat != null)
                            fMonat.action(IExport_Basis.ACTION_SHARE,
                                    ASettings.aktJob, mStorageHelper);
                        break;
                    case 2:
                        if (fJahr != null)
                            fJahr.action(IExport_Basis.ACTION_SHARE,
                                    ASettings.aktJob, mStorageHelper);
                        break;
                    case 3:
                        if (fZeitraum != null)
                            fZeitraum.action(IExport_Basis.ACTION_SHARE,
                                    ASettings.aktJob, mStorageHelper);
                        break;
                    case 4:
                        if (fEort != null)
                            fEort.action(IExport_Basis.ACTION_SHARE,
                                    ASettings.aktJob, mStorageHelper);
                        break;
                }
                return true;
            }*/
        return super.onOptionsItemSelected(item);
    }

    /**
     * A {@link FragmentStateAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    private class SectionsPagerAdapter extends FragmentStateAdapter implements IExportFinishListener {
        SectionsPagerAdapter(FragmentManager fm, Lifecycle l) {
            super(fm, l);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
                switch (position){
                    case 0:
                        exportFragmente[position] = Export_Fragment_Woche
                                .newInstance(this, exportDatum.getTimeInMillis());
                        break;
                    case 2:
                        exportFragmente[position] = Export_Fragment_Jahr
                                .newInstance(this, exportDatum.get(Calendar.YEAR));
                        break;
                    case 3:
                        exportFragmente[position] = Export_Fragment_Zeitraum
                                .newInstance(this, exportDatum.getTimeInMillis());
                        break;
                    case 4:
                        exportFragmente[position] = Export_Fragment_Einsatzort
                                .newInstance(this, exportDatum.getTimeInMillis());
                        break;
                    default :
                        exportFragmente[position] = Export_Fragment_Monat
                                .newInstance(this, exportDatum.getTimeInMillis());

                }
            return (Fragment) exportFragmente[position];
            /*switch (position) {
                case 0:
                    fWoche = Export_Fragment_Woche.newInstance(this, EXPORT_DATUM.getTimeInMillis());
                    return fWoche;
                case 2:
                    fJahr = Export_Fragment_Jahr.newInstance(this, EXPORT_DATUM.get(Calendar.YEAR));
                    return fJahr;
                case 3:
                    fZeitraum = Export_Fragment_Zeitraum.newInstance(this, EXPORT_DATUM.getTimeInMillis());
                    return fZeitraum;
                case 4:
                    if (fEort == null) {
                        fEort = Export_Fragment_Einsatzort.newInstance(this, EXPORT_DATUM.getTimeInMillis());
                    }
                    return fEort;
                default:
                    fMonat = Export_Fragment_Monat.newInstance(this, EXPORT_DATUM.getTimeInMillis());
                    return fMonat;
            }*/
        }

        @Override
        public int getItemCount() {
            if (ASettings.aktJob.isOptionSet(Arbeitsplatz.OPT_WERT_EORT))
                return maxFragments;
            else
                return maxFragments -1;
        }

        /*
         * Der export des Berichts war erfolgreich und kann nun weiter gereicht werden
         */
        @Override
        public void onExportFinisch(int action, final int typ, int periode, final ArrayList<String> dateinamen, Datum starttag, Datum endtag) {
            PackageManager pm = mContext.getPackageManager();
            ArrayList<Uri> mUri = new ArrayList<>();
            for (String dateiname : dateinamen) {
                Uri uri = mStorageHelper.getDateiUri(dateiname);
                if(uri != null) {
                    mUri.add(uri);
                }
            }

            if (!mUri.isEmpty()) {
                switch (action) {
                    case IExport_Basis.ACTION_SEND:
                        StringBuilder subject = new StringBuilder();

                        //Datei als ausgewählter Typ mailen
                        subject.append(getString(R.string.mail_arbeitszeit)).append(" ");
                        subject.append(ASettings.mPreferenzen.getString(ISettings.KEY_USERNAME, "")).append(" ");
                        switch (periode) {
                            case IExport_Basis.PERIODE_WOCHE:
                                subject.append(getString(R.string.mail_arbeitswoche,
                                        starttag.get(Calendar.WEEK_OF_YEAR),
                                        starttag.get(Calendar.YEAR)
                                ));
                                break;
                            case IExport_Basis.PERIODE_MONAT:
                                subject.append(getString(R.string.mail_arbeitsmonat,
                                        starttag.get(Calendar.MONTH),
                                        starttag.get(Calendar.YEAR)
                                ));
                                break;
                            case IExport_Basis.PERIODE_JAHR:
                                subject.append(getString(R.string.mail_arbeitsjahr,
                                        starttag.get(Calendar.YEAR)
                                ));
                                break;
                            case IExport_Basis.PERIODE_ZEITRAUM:
                                subject.append(getString(R.string.mail_zeitraum,
                                        starttag.getString_Datum(mContext),
                                        endtag.getString_Datum(mContext))

                                );
                                break;
                            case IExport_Basis.PERIODE_EORT:
                                subject.append(getString(R.string.mail_eort,
                                        starttag.getString_Datum(mContext),
                                        endtag.getString_Datum(mContext)
                                ));
                                break;
                        }

                        Intent emailIntent = new Intent(/*mUri.size() > 1 ? Intent.ACTION_SEND_MULTIPLE : Intent.ACTION_SEND*/);
                        emailIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                        String[] empfaenger = ASettings.aktJob.getEmail().split(",\\s*");

                        if (empfaenger.length > 0) {
                            emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{empfaenger[0]});
                            if (empfaenger.length > 1) {
                                String[] bcc = new String[empfaenger.length - 1];
                                int i = 1;
                                while (i < empfaenger.length) {
                                    bcc[i - 1] = empfaenger[i];
                                    i++;
                                }
                                emailIntent.putExtra(Intent.EXTRA_BCC, bcc);
                            }
                        } else {
                            emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{""});
                        }

                        emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject.toString());
                        emailIntent.putExtra(Intent.EXTRA_TEXT, ASettings.aktJob.getEmailText());
                        //emailIntent.setType("text/plain");
                        //emailIntent.setType("message/rfc822");
                        switch (typ) {
                            case IExport_Basis.TYP_PDF:
                                emailIntent.setType(IExport_Basis.DATEI_TYP_PDF);
                                break;
                            case IExport_Basis.TYP_CAL_ICS:
                                emailIntent.setType(IExport_Basis.DATEI_TYP_ICS);
                                break;
                            default:
                                emailIntent.setType(IExport_Basis.DATEI_TYP_CSV);
                                break;
                        }
                        if (mUri.size() == 1){
                            emailIntent.setAction(Intent.ACTION_SEND);
                            emailIntent.putExtra(Intent.EXTRA_STREAM, mUri.get(0));
                        } else {
                            emailIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
                            emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, mUri);
                        }

                        if (emailIntent.resolveActivity(pm) != null) {
                            try {
                                startActivity(
                                        Intent.createChooser(
                                                emailIntent,
                                                getString(R.string.mailwahl))
                                );
                            } catch (SecurityException se) {
                                Toast.makeText(mContext, R.string.app_keinZugriff, Toast.LENGTH_LONG).show();
                            }
                        } else {
                            Toast.makeText(mContext, R.string.no_app, Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case IExport_Basis.ACTION_SHARE:
                        Intent shareIntent = new Intent();
                        shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        if(mUri.size() == 1){
                            shareIntent.setAction(Intent.ACTION_SEND);
                            shareIntent.putExtra(Intent.EXTRA_STREAM, mUri.get(0));
                        } else {
                            shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
                            shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, mUri);
                        }
                        switch (typ) {
                            case IExport_Basis.TYP_PDF:
                                shareIntent.setType(IExport_Basis.DATEI_TYP_PDF);
                                break;
                            case IExport_Basis.TYP_CAL_ICS:
                                shareIntent.setType(IExport_Basis.DATEI_TYP_ICS);
                                break;
                            default:
                                shareIntent.setType(IExport_Basis.DATEI_TYP_CSV);
                                break;

                        }
                        if (shareIntent.resolveActivity(pm) != null) {
                            try {
                                startActivity(
                                        Intent.createChooser(
                                                shareIntent,
                                                getString(R.string.zielwahl))
                                );
                            } catch (SecurityException se) {
                                Toast.makeText(mContext, R.string.app_keinZugriff, Toast.LENGTH_LONG).show();
                            }
                        } else {
                            Toast.makeText(mContext, R.string.no_app, Toast.LENGTH_SHORT).show();
                        }
                        break;
                    default:
                        if (!ASettings.mPreferenzen.contains(ISettings.KEY_ANTWORT_OEFFNEN)) {
                            @SuppressLint("InflateParams") final View vFrage = LayoutInflater.from(mContext).inflate(R.layout.fragment_dialog_frage_open, null);
                            androidx.appcompat.app.AlertDialog.Builder aFrage = new androidx.appcompat.app.AlertDialog.Builder(mContext);
                            aFrage.setView(vFrage);
                            aFrage.setPositiveButton(R.string.open, (dialog, which) -> {
                                // Antwort des Users merken
                                AppCompatCheckBox mMerken = vFrage.findViewById(R.id.F_button_merken);
                                if (mMerken.isChecked()) {
                                    SharedPreferences.Editor mEdit = ASettings.mPreferenzen.edit();
                                    mEdit.putBoolean(ISettings.KEY_ANTWORT_OEFFNEN, true).apply();
                                }
                                //Datei als ausgewählter Typ anzeigen
                                Intent openIntent = new Intent(Intent.ACTION_VIEW);
                                openIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP /*| Intent.FLAG_ACTIVITY_NEW_TASK*/);

                                switch (typ) {
                                    case IExport_Basis.TYP_PDF:
                                        openIntent.setDataAndType(
                                                mUri.get(0), IExport_Basis.DATEI_TYP_PDF);
                                        break;
                                    case IExport_Basis.TYP_CAL_ICS:
                                        openIntent.setDataAndType(
                                                mUri.get(0), IExport_Basis.DATEI_TYP_ICS);
                                        break;
                                    default:
                                        openIntent.setDataAndType(
                                                mUri.get(0), IExport_Basis.DATEI_TYP_CSV);
                                }
                                openIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                try {
                                    PackageManager pm1 = getPackageManager();
                                    if (openIntent.resolveActivity(pm1) != null) {
                                        try {
                                            startActivity(openIntent);
                                        } catch (SecurityException se) {
                                            Toast.makeText(mContext, R.string.app_keinZugriff, Toast.LENGTH_LONG).show();
                                        }
                                    } else {
                                        ToastMissingAPP(typ);
                                    }
                                } catch (ActivityNotFoundException e) {
                                    ToastMissingAPP(typ);
                                }

                            });
                            aFrage.setNegativeButton(R.string.noopen, (dialog, which) -> {
                                // nichts machen, nur den Dialog schliessen
                                // Antwort des Users merken
                                AppCompatCheckBox mMerken = vFrage.findViewById(R.id.F_button_merken);
                                if (mMerken.isChecked()) {
                                    SharedPreferences.Editor mEdit = ASettings.mPreferenzen.edit();
                                    mEdit.putBoolean(ISettings.KEY_ANTWORT_OEFFNEN, false).apply();
                                }
                            });
                            aFrage.create().show();

                        } else {
                            if (ASettings.mPreferenzen.getBoolean(ISettings.KEY_ANTWORT_OEFFNEN, false)) {
                                //Viewer für Datei suchen
                                Intent openIntent = new Intent(Intent.ACTION_VIEW);
                                openIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP/* | Intent.FLAG_ACTIVITY_NEW_TASK*/);

                                switch (typ) {
                                    case IExport_Basis.TYP_PDF:
                                        openIntent.setDataAndType(
                                                mUri.get(0), IExport_Basis.DATEI_TYP_PDF);
                                        break;
                                    case IExport_Basis.TYP_CAL_ICS:
                                        openIntent.setDataAndType(
                                                mUri.get(0), IExport_Basis.DATEI_TYP_ICS);
                                        break;
                                    default:
                                        openIntent.setDataAndType(
                                                mUri.get(0), IExport_Basis.DATEI_TYP_CSV);
                                }
                                openIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                try {
                                    if (openIntent.resolveActivity(pm) != null) {
                                        try {
                                            startActivity(openIntent);
                                        } catch (SecurityException se) {
                                            Toast.makeText(mContext, R.string.app_keinZugriff, Toast.LENGTH_LONG).show();
                                        }
                                    } else {
                                        ToastMissingAPP(typ);
                                    }
                                } catch (ActivityNotFoundException e) {
                                    ToastMissingAPP(typ);
                                }
                            }
                        }
                }
            }
        }
    }

    // Meldung über fehlende App zur Anzeige eines Dateityps anzeigen
    void ToastMissingAPP(int typ) {
        switch (typ) {
            case IExport_Basis.TYP_PDF:
                Toast.makeText(ExportActivity.this, R.string.no_pdf_reader, Toast.LENGTH_SHORT).show();
                break;
            case IExport_Basis.TYP_CAL_CSV:
            case IExport_Basis.TYP_CSV:
                Toast.makeText(ExportActivity.this, R.string.no_csv_reader, Toast.LENGTH_SHORT).show();
                break;
            case IExport_Basis.TYP_CAL_ICS:
                Toast.makeText(ExportActivity.this, R.string.no_calendar_app, Toast.LENGTH_SHORT).show();
                break;
            default:
                Toast.makeText(ExportActivity.this, R.string.no_app, Toast.LENGTH_SHORT).show();
                break;
        }
    }
}
