/* 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;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.preference.PreferenceManager;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Objects;

import askanimus.arbeitszeiterfassung2.datensicherung.Datensicherung_Activity;
import askanimus.arbeitszeiterfassung2.export.ExportActivity;
import askanimus.arbeitszeiterfassung2.setup.ASettings;
import askanimus.arbeitszeiterfassung2.setup.ISettings;
import askanimus.arbeitszeiterfassung2.setup.SettingsActivity;
import askanimus.arbeitszeiterfassung2.suche.Suche_Activity;
import askanimus.betterpickers.calendardatepicker.CalendarDatePickerDialogFragment;
import askanimus.betterpickers.calendardatepicker.MonthAdapter;
import askanimus.betterpickers.expirationpicker.ExpirationPickerBuilder;
import askanimus.betterpickers.expirationpicker.ExpirationPickerDialogFragment;
import askanimus.betterpickers.numberpicker.NumberPickerBuilder;
import askanimus.betterpickers.numberpicker.NumberPickerDialogFragment;
import askanimus.betterpickers.weeknumberpicker.WeeknumberPickerBuilder;
import askanimus.betterpickers.weeknumberpicker.WeeknumberPickerDialogFragment;

/**
 * Fragment used for managing interactions for and presentation of a navigation drawer.
 * See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
 * design guidelines</a> for a complete explanation of the behaviors implemented here.
 */
public class NavigationDrawerFragment extends Fragment implements
        WeeknumberPickerDialogFragment.WeeknumberPickerDialogHandler,
        NumberPickerDialogFragment.NumberPickerDialogHandlerV2,
        ExpirationPickerDialogFragment.ExpirationPickerDialogHandler {
    final private int POS_JOB = 0;
    final private int POS_JAHR = 1;
    final private int POS_MONAT = 2;
    final private int POS_WOCHE = 3;
    final private int POS_TAG = 4;
    final private int POS_FEIERTAGE = 5;
    final private int POS_STEMPEL = 6;
    final private int POS_CHARTS = 7;
    final private int POS_ICONS = 8;
    final int[] nViews = {
            ISettings.VIEW_JOB,
            ISettings.VIEW_JAHR,
            ISettings.VIEW_MONAT,
            ISettings.VIEW_WOCHE,
            ISettings.VIEW_TAG,
            ISettings.VIEW_FEIERTAGE,
            ISettings.VIEW_STEMPELUHR,
            ISettings.VIEW_CHARTS,
            POS_ICONS
    };
    /**
     * Remember the position of the selected item.
     */
    private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";

    /**
     * Per the design guidelines, you should show the drawer on launch until the user manually
     * expands it. This shared preference tracks this.
     */
    private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";

    /**
     * A pointer to the current callbacks instance (the Activity).
     */
    private NavigationDrawerCallbacks mCallbacks;

    private final Fragment mFragment;
    /**
     * Helper component that ties the action bar to the navigation drawer.
     */
    private ActionBarDrawerToggle mDrawerToggle;

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerListView;

    private Context mContext;

    private View mFragmentContainerView;

    private int mCurrentSelectedPosition ;
    private boolean mFromSavedInstanceState;
    private boolean mUserLearnedDrawer;

    public NavigationDrawerFragment() {
        mCurrentSelectedPosition = 0;
        mFragment = this;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Read in the flag indicating whether or not the user has demonstrated awareness of the
        // drawer. See PREF_USER_LEARNED_DRAWER for details.
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(requireActivity());
        mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, true);

        if (savedInstanceState != null) {
            mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
            mFromSavedInstanceState = true;
        }

        // Select either the default item (0) or the last selected item.
        //selectItem(mCurrentSelectedPosition);
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Indicate that this fragment would like to influence the set of actions in the action bar.
        setHasOptionsMenu(true);
    }


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mDrawerListView = (ListView) inflater.inflate(
                R.layout.fragment_main_nav_drawer, container, false);

        return mDrawerListView;
    }

    void Resume(){
        if (mContext != null) {
            NavigationListAdapter adapter = new NavigationListAdapter(mContext);
            mDrawerListView.setAdapter(adapter);
            mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    selectItem(position);
                }
            });
            mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);

            mDrawerListView.setBackgroundColor(ASettings.aktJob.getFarbe_Hintergrund());
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mContext = getContext();
        ASettings.init(mContext, this::Resume);
    }

    boolean isDrawerOpen() {
        return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
    }

    protected void OpenDrawer(){
        mDrawerLayout.openDrawer(mFragmentContainerView);
    }

    void CloseDrawer(){
        mDrawerLayout.closeDrawer(mFragmentContainerView);
    }

    /**
     * Users of this fragment must call this method to set up the navigation drawer interactions.
     *
     * @param fragmentId   The android:id of this fragment in its activity's layout.
     * @param drawerLayout The DrawerLayout containing this fragment's UI.
     */
    public void setUp(int fragmentId, DrawerLayout drawerLayout) {
        mFragmentContainerView = drawerLayout.findViewById(fragmentId);
        mDrawerLayout = drawerLayout;

        // set a custom shadow that overlays the main content when the drawer opens
        //mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

        // set up the drawer's list view with items and click listener

        ActionBar actionBar = getActionBar();
        if(actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }
        //actionBar.setBackgroundDrawable(new ColorDrawable(Einstellungen.aktJob.getFarbe()));

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the navigation drawer and the action bar app icon.
        mDrawerToggle = new ActionBarDrawerToggle(
                getActivity(),                    /* host Activity */
                mDrawerLayout,                    /* DrawerLayout object */
                //R.drawable.ic_drawer,             /* nav drawer image to replace 'Up' caret */
                R.string.navigation_drawer_open,  /* "open drawer" description for accessibility */
                R.string.navigation_drawer_close  /* "close drawer" description for accessibility */
        ) {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                if (!isAdded()) {
                    return;
                }
                ActionBar actionBar = getActionBar();
                actionBar.setDisplayShowTitleEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
                //getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                if (!isAdded()) {
                    return;
                }

                if (!mUserLearnedDrawer) {
                    // The user manually opened the drawer; store this flag to prevent auto-showing
                    // the navigation drawer automatically in the future.
                    mUserLearnedDrawer = true;
                    ASettings.mPreferenzen.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
                    /*SharedPreferences sp = PreferenceManager
                            .getDefaultSharedPreferences(getActivity());
                    sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();*/
                }

                ActionBar actionBar = getActionBar();
                actionBar.setDisplayShowTitleEnabled(false);
                //getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }
        };

        // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
        // per the navigation drawer design guidelines.
        if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
            mDrawerLayout.openDrawer(mFragmentContainerView);
        }

        // Defer code dependent on restoration of previous instance state.
        mDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
                mDrawerToggle.syncState();
            }
        });

        //mDrawerLayout.setDrawerListener(mDrawerToggle);
        mDrawerLayout.addDrawerListener(mDrawerToggle);
    }

    private void selectItem(int position) {
        mCurrentSelectedPosition = position;
        /*if (mDrawerListView != null) {
            mDrawerListView.setItemChecked(position, true);
        }
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawer(mFragmentContainerView);
        }*/
        if (mCallbacks != null) {
            mCallbacks.onNavigationDrawerItemSelected(nViews[position], new Datum(ASettings.aktDatum));
        }
    }

    /*@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mCallbacks = (NavigationDrawerCallbacks) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
        }
    }*/

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        try {
            mCallbacks = (NavigationDrawerCallbacks) getActivity();
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
        }

    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Forward the new configuration the drawer toggle component.
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    /*@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // If the drawer is open, show the global app actions in the action bar. See also
        // showGlobalContextActionBar, which controls the top-left area of the action bar.
        if (mDrawerLayout != null && isDrawerOpen()) {
            inflater.inflate(R.menu.global, menu);
            showGlobalContextActionBar();
        }
        super.onCreateOptionsMenu(menu, inflater);
    }*/

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        /*if (item.getItemId() == R.id.action_example) {
            Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
            return true;
        }*/

        return super.onOptionsItemSelected(item);
    }

    /**
     * Per the navigation drawer design guidelines, updates the action bar to show the global app
     * 'context', rather than just what's in the current screen.

    private void showGlobalContextActionBar() {
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(true);
        //actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setTitle(R.string.app_name);
    }*/

    private ActionBar getActionBar() {
        if (getActivity() != null) {
            return ((AppCompatActivity) getActivity()).getSupportActionBar();
        } else
            return null;
    }

    @Override
    public void onDialogNumberSet(int reference, BigInteger number, double decimal, boolean isNegative, BigDecimal fullNumber) {
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawer(mFragmentContainerView);
        }
        Datum mDatum = new Datum (ASettings.aktDatum.getDate(), ASettings.aktJob.getWochenbeginn());
        mDatum.setJahr(number.intValue());
        if(mCallbacks != null)
            mCallbacks.onNavigationDrawerItemSelected(POS_JAHR, mDatum);
    }

    @Override
    public void onDialogExpirationSet(int reference, int year, int monthOfYear) {
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawer(mFragmentContainerView);
        }
        Datum mDatum = new Datum (
                year,
                monthOfYear,
                ASettings.aktJob.getMonatsbeginn(),
                ASettings.aktJob.getWochenbeginn());

        if(mCallbacks != null)
            mCallbacks.onNavigationDrawerItemSelected(POS_MONAT, mDatum);

    }

    @Override
    public void onDialogWeeknumberSet(int reference, int year, int week) {
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawer(mFragmentContainerView);
        }
        Datum mDatum = new Datum (
                year,
                1,
                ASettings.aktJob.getMonatsbeginn(),
                ASettings.aktJob.getWochenbeginn());
        mDatum.setWoche(week);

        if(mCallbacks != null)
            mCallbacks.onNavigationDrawerItemSelected(POS_WOCHE, mDatum);
    }


    /**
     * Callbacks interface that all activities using this fragment must implement.
     */
    public interface NavigationDrawerCallbacks {
        /**
         * Called when an item in the navigation drawer is selected.
         */
        void onNavigationDrawerItemSelected(int position, Datum datum);

        // wenn das Handbuch angezeigt werden soll dann diesen Aufruf starten
        void onNavigationDrawerIconSelected(int icon);
    }


    /**********************************************************************************************
     * ******************** Unterklasse für die Navigationsliste **********************************
     **********************************************************************************************/
    class NavigationListAdapter extends BaseAdapter {
        private final LayoutInflater mInflater;
        private final Context mContext;

        NavigationListAdapter(Context context) {
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mContext = context;
        }

        @Override
        public int getCount() {
            return nViews.length ;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            switch (position){
                case POS_JOB :
                    convertView = mInflater.inflate(R.layout.fragment_nav_arbeitsplatz , parent, false);
                    bindViewJob(convertView);
                    break;
                case POS_JAHR :
                    convertView = mInflater.inflate( R.layout.fragment_nav_jahr, parent, false);
                    binViewJahr(convertView);
                    break;
                case POS_MONAT :
                    convertView = mInflater.inflate(R.layout.fragment_nav_monat , parent, false);
                    binViewMonat(convertView);
                    break;
                case POS_WOCHE :
                    convertView = mInflater.inflate(R.layout.fragment_nav_woche, parent, false);
                    binViewWoche(convertView);
                    break;
                case POS_TAG :
                    convertView = mInflater.inflate(R.layout.fragment_nav_tag , parent, false);
                    binViewTag(convertView);
                    break;
                case POS_ICONS :
                    convertView = mInflater.inflate(R.layout.fragment_nav_icons , parent, false);
                    binViewIcons(convertView);
                    break;
                case POS_CHARTS:
                    convertView = mInflater.inflate(R.layout.fragment_nav_allgemein, parent, false);
                    bindViewCharts(convertView);
                    break;
                case POS_STEMPEL:
                    convertView = mInflater.inflate(R.layout.fragment_nav_allgemein, parent, false);
                    bindViewStempel(convertView);
                    break;
                case POS_FEIERTAGE:
                    convertView = mInflater.inflate(R.layout.fragment_nav_allgemein, parent, false);
                    bindViewFeiertage(convertView);
                    break;
            }

            return convertView;
        }

        // die einzelnen Anzeigen
        private void bindViewJob(View view) {
            TextView mName = view.findViewById(R.id.N_job_name);
            TextView mHint = view.findViewById(R.id.N_job_hint_name);

            // Werte setzen
            view.setBackgroundColor(ASettings.aktJob.getFarbe());
            mName.setText(ASettings.aktJob.getName());
            if (ASettings.aktJob.isSetEnde() && ASettings.aktDatum.liegtNach(ASettings.letzterAnzeigeTag)) {
                String sHint = ASettings.aktJob.getAnschrift().replace("\n", "; ");
                sHint += "\n\n";
                sHint += getString(R.string.aufzeichnung_beendet, ASettings.letzterAnzeigeTag.getString_Datum(mContext));
                mHint.setText(sHint);
            } else {
                mHint.setText(ASettings.aktJob.getAnschrift().replace("\n", "; "));
            }

            mName.setTextColor(ASettings.aktJob.getFarbe_Schrift_Titel());
            mHint.setTextColor(ASettings.aktJob.getFarbe_Schrift_Titel());
            // Handler registrieren

        }

        private void binViewJahr(View view){
            TextView mName = view.findViewById(R.id.N_jahr_name);
            TextView mHint = view.findViewById(R.id.N_jahr_hint_name);
            ImageView iButton = view.findViewById(R.id.N_jahr_button);

            Datum mJahr;

            final int mMinJahr;
           if(ASettings.aktJob.getStartDatum().get(Calendar.DAY_OF_MONTH) < ASettings.aktJob.getMonatsbeginn())
                mMinJahr= ASettings.aktJob.getStartDatum().get(Calendar.YEAR) -1;
            else
                mMinJahr= ASettings.aktJob.getStartDatum().get(Calendar.YEAR);

            // Werte setzen
            if (ASettings.aktJob.isEndeAufzeichnung(ASettings.aktDatum)) {
                mName.setText(getString(R.string.letztes, getString(R.string.jahr)));
                mJahr = ASettings.aktJob.getAbrechnungsmonat(ASettings.letzterAnzeigeTag);
                mHint.setText(String.valueOf(mJahr.get(Calendar.YEAR)));
            } else if (ASettings.aktJob.isStartAufzeichnung(ASettings.aktDatum)
                    && !ASettings.aktDatum.liegtNach(ASettings.letzterAnzeigeTag)) {
                mName.setText(getString(R.string.aktuelles, getString(R.string.jahr)));
                mJahr = ASettings.aktJob.getAbrechnungsmonat(ASettings.aktDatum);
                mHint.setText(String.valueOf(mJahr.get(Calendar.YEAR)));

                // Handler registrieren
                iButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        NumberPickerBuilder prozentPicker = new NumberPickerBuilder()
                                .setFragmentManager(getParentFragmentManager())
                                .setStyleResId(ASettings.themePicker)
                                .setMinNumber(BigDecimal.valueOf(mMinJahr))
                                .setMaxNumber(BigDecimal.valueOf(ASettings.letzterAnzeigeTag.get(Calendar.YEAR)))
                                .setLabelText(getString(R.string.jahr))
                                .setCurrentNumber(20)
                                .setPlusMinusVisibility(View.INVISIBLE)
                                .setDecimalVisibility(View.INVISIBLE)
                                .setReference(R.id.N_jahr_button)
                                .setTargetFragment(mFragment);
                        prozentPicker.show();

                    }
                });
            } else {
                mName.setVisibility(View.GONE);
                mHint.setVisibility(View.GONE);
                iButton.setVisibility(View.GONE);
            }

        }

        private void binViewMonat(View view){
            String mTextHint;
            TextView mName = view.findViewById(R.id.N_monat_name);
            TextView mHint = view.findViewById(R.id.N_monat_hint_name);
            ImageView iButton = view.findViewById(R.id.N_monat_button);

            //Calendar mCal = Calendar.getInstance();
            Datum mKal;

            // Werte setzen
            if (ASettings.aktJob.isEndeAufzeichnung(ASettings.aktDatum)) {
                mName.setText(getString(R.string.letzter, getString(R.string.monat)));
                mKal = ASettings.aktJob.getAbrechnungsmonat(ASettings.letzterAnzeigeTag);
                mTextHint = mKal.getString_Monat_Jahr(ASettings.aktJob.getMonatsbeginn(), false);
                mHint.setText(mTextHint);
            } else if (ASettings.aktJob.isStartAufzeichnung(ASettings.aktDatum)
                    && !ASettings.aktDatum.liegtNach(ASettings.letzterAnzeigeTag)) {
                mName.setText(getString(R.string.aktueller, getString(R.string.monat)));
                mKal = ASettings.aktJob.getAbrechnungsmonat(ASettings.aktDatum);

                mTextHint = mKal.getString_Monat_Jahr(ASettings.aktJob.getMonatsbeginn(), false);
                mHint.setText(mTextHint);
            } else {
                mName.setVisibility(View.GONE);
                mHint.setVisibility(View.GONE);
                iButton.setVisibility(View.GONE);
            }

            // Handler registrieren
            if(iButton.getVisibility() == View.VISIBLE) {
                iButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ExpirationPickerBuilder epb = new ExpirationPickerBuilder()
                                .setFragmentManager(getParentFragmentManager())
                                .setStyleResId(ASettings.themePicker)
                                .setMinDate(ASettings.aktJob.getStartDatum().get(Calendar.YEAR), ASettings.aktJob.getStartDatum().get(Calendar.MONTH) - 1)
                                .setMaxDate(ASettings.letzterAnzeigeTag.get(Calendar.YEAR), ASettings.letzterAnzeigeTag.get(Calendar.MONTH) - 1)
                                .setReference(view.getId())
                                .setTargetFragment(mFragment);
                        epb.show();
                    }
                });
            }
        }

        private void binViewWoche(View view) {
            String mTextHint;
            final Datum mDatum;
            int addTage;
            TextView mName = (TextView) view.findViewById(R.id.N_woche_name);
            TextView mHint = (TextView) view.findViewById(R.id.N_woche_hint_name);
            ImageView iButton = (ImageView) view.findViewById(R.id.N_woche_button);

            // Werte setzen
            if (ASettings.aktJob.isEndeAufzeichnung(ASettings.aktDatum)) {
                mDatum = new Datum(ASettings.aktJob.getEndDatum().getDate(), ASettings.aktJob.getWochenbeginn());
                mDatum.setDatumAufWochenbeginn();
                addTage = mDatum.tageBis(ASettings.aktJob.getEndDatum());
                mName.setText(getString(R.string.letzte, getString(R.string.woche)));

                mTextHint = mDatum.getString_Woche_Jahr();
                mTextHint += "\n";
                mTextHint += mDatum.getString_Datum_Bereich(mContext, 0, addTage, Calendar.DAY_OF_WEEK);
                mHint.setText(mTextHint);
            } else if (ASettings.aktJob.isStartAufzeichnung(ASettings.aktDatum)
                    && !ASettings.aktDatum.liegtNach(ASettings.letzterAnzeigeTag)) {
                mDatum = new Datum(ASettings.aktDatum.getDate(), ASettings.aktJob.getWochenbeginn());
                mDatum.setDatumAufWochenbeginn();
                addTage = 6;
                mName.setText(getString(R.string.aktuelle, getString(R.string.woche)));

                mTextHint = mDatum.getString_Woche_Jahr();
                mTextHint += "\n";
                mTextHint += mDatum.getString_Datum_Bereich(mContext, 0, addTage, Calendar.DAY_OF_WEEK);

                mHint.setText(mTextHint);
            } else {
                mName.setVisibility(View.GONE);
                mHint.setVisibility((View.GONE));
                iButton.setVisibility(View.GONE);
            }

            // Handler registrieren
            if(iButton.getVisibility() == View.VISIBLE) {
                iButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        WeeknumberPickerBuilder wnp = new WeeknumberPickerBuilder()
                                .setFragmentManager(getParentFragmentManager())
                                .setStyleResId(ASettings.themePicker)
                                .setMinDate(ASettings.aktJob.getStartDatum().get(Calendar.YEAR), ASettings.aktJob.getStartDatum().get(Calendar.WEEK_OF_YEAR))
                                .setMaxDate(ASettings.letzterAnzeigeTag.get(Calendar.YEAR), ASettings.letzterAnzeigeTag.get(Calendar.WEEK_OF_YEAR))
                                .setReference(view.getId())
                                .setTargetFragment(mFragment);
                        wnp.show();
                    }
                });
            }
        }

        private void binViewTag(View view) {
            TextView mName = view.findViewById(R.id.N_tag_name);
            TextView mHint = view.findViewById(R.id.N_tag_hint_name);
            ImageView iButton = view.findViewById(R.id.N_tag_button);

            if (ASettings.aktJob.isEndeAufzeichnung(ASettings.aktDatum)
                    || ASettings.aktDatum.liegtNach(ASettings.letzterAnzeigeTag)) {
                mName.setVisibility(View.GONE);
                mHint.setVisibility(View.GONE);
                iButton.setVisibility(View.GONE);
            } else if (ASettings.aktJob.isStartAufzeichnung(ASettings.aktDatum)) {
                final FragmentManager fManager = getFragmentManager();
                // Werte setzen
                mName.setText(getString(R.string.aktueller, getString(R.string.tag)));
                mHint.setText(ASettings.aktDatum.getString_Datum(mContext));
                // Handler registrieren
                iButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Datum mAktuell = new Datum(ASettings.aktDatum.getDate(), ASettings.aktJob.getWochenbeginn());
                        Datum mEnde = new Datum(ASettings.letzterAnzeigeTag.getDate(), ASettings.aktJob.getWochenbeginn());
                        CalendarDatePickerDialogFragment vonKalenderPicker =
                                new CalendarDatePickerDialogFragment()
                                        .setOnDateSetListener(new CalendarDatePickerDialogFragment.OnDateSetListener() {
                                            @Override
                                            public void onDateSet(CalendarDatePickerDialogFragment dialog, int year, int monthOfYear, int dayOfMonth) {
                                                if (mDrawerLayout != null) {
                                                    mDrawerLayout.closeDrawer(mFragmentContainerView);
                                                }
                                                Datum mDatum = new Datum(ASettings.aktJob.getWochenbeginn());
                                                mDatum.set(year, monthOfYear + 1, dayOfMonth);
                                                //mAktuell.set(year, monthOfYear + 1, dayOfMonth);
                                                if (mCallbacks != null)
                                                    mCallbacks.onNavigationDrawerItemSelected(POS_TAG, mDatum);
                                            }
                                        })
                                        .setFirstDayOfWeek(ASettings.aktJob.getWochenbeginn())
                                        .setPreselectedDate(
                                                mAktuell.get(Calendar.YEAR),
                                                mAktuell.get(Calendar.MONTH) - 1,
                                                mAktuell.get(Calendar.DAY_OF_MONTH))
                                        .setDateRange(
                                                new MonthAdapter.CalendarDay(
                                                        ASettings.aktJob.getStartDatum().get(Calendar.YEAR),
                                                        ASettings.aktJob.getStartDatum().get(Calendar.MONTH) - 1,
                                                        ASettings.aktJob.getStartDatum().get(Calendar.DAY_OF_MONTH)),
                                                new MonthAdapter.CalendarDay(
                                                        mEnde.get(Calendar.YEAR),
                                                        mEnde.get(Calendar.MONTH) - 1,
                                                        mEnde.get(Calendar.DAY_OF_MONTH)));
                        if (ASettings.isThemaDunkel) {
                            vonKalenderPicker.setThemeDark();
                        } else {
                            vonKalenderPicker.setThemeLight();
                        }
                        if (fManager != null) {
                            vonKalenderPicker.show(fManager, getString(R.string.tag));
                        }
                    }
                });
            } else {

                mName.setVisibility(View.GONE);
                mHint.setVisibility(View.GONE);
                iButton.setVisibility(View.GONE);
            }
        }

        private void binViewIcons(View view) {
            ImageView iEinstellungen = (ImageView) view.findViewById(R.id.N_icon_einstellungen);
            ImageView iSicherung = (ImageView) view.findViewById(R.id.N_icon_sicherung);
            ImageView ihilfe = (ImageView) view.findViewById(R.id.N_icon_hilfe);
            ImageView iExport = (ImageView) view.findViewById(R.id.N_icon_export);
            ImageView iSuche = (ImageView) view.findViewById(R.id.N_icon_suche);
            final Activity mAktivity = getActivity();


            // Handler registrieren
            if (mAktivity != null) {
                iSuche.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        final Dialog mDialog = new Dialog(mContext);

                        mDialog.setTitle(R.string.suche);

                        mDialog.setContentView(R.layout.fragment_suche);
                        final SearchView mSuche = mDialog.findViewById(R.id.SU_suche);
                        mSuche.setQueryHint(getString(R.string.suche));
                        mSuche.setIconified(false);
                        mSuche.setSubmitButtonEnabled(true);
                        mSuche.setOnCloseListener(new SearchView.OnCloseListener() {
                            @Override
                            public boolean onClose() {
                                if (mSuche.getQuery().length() > 0)
                                    mSuche.clearFocus();
                                else
                                    mDialog.dismiss();
                                return true;
                            }
                        });
                        mSuche.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                            @Override
                            public boolean onQueryTextSubmit(String query) {
                                String mSuchstring = mSuche.getQuery().toString();
                                mSuche.clearFocus();
                                mDialog.cancel();
                                Intent iSuche = new Intent();
                                iSuche.setClass(mContext, Suche_Activity.class);
                                iSuche.putExtra(ISettings.KEY_SUCHE_STRING, mSuchstring);
                                startActivity(iSuche);
                                mAktivity.finish();
                                return true;
                            }

                            @Override
                            public boolean onQueryTextChange(String newText) {
                                return false;
                            }
                        });


                        mDialog.show();
                    }
                });
                iEinstellungen.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent iSettings = new Intent();
                        iSettings.setClass(mAktivity, SettingsActivity.class);
                        iSettings.putExtra(ISettings.KEY_EDIT_JOB, ASettings.aktJob.getId());
                        iSettings.putExtra(ISettings.KEY_INIT_SEITE, ISettings.SETUP_SEITE_ALLGEMEIN);

                        startActivity(iSettings);
                        mAktivity.finish();

                    }
                });

                iExport.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent iExportIntent = new Intent();
                        iExportIntent.setClass(mAktivity, ExportActivity.class);
                        iExportIntent.putExtra(ISettings.KEY_JOBID, ASettings.aktJob.getId());
                        startActivity(iExportIntent);
                        mAktivity.finish();
                    }
                });

                iSicherung.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent iSicherungIntent = new Intent();
                        iSicherungIntent.setClass(mAktivity, Datensicherung_Activity.class);
                        //iSicherungIntent.putExtra(Einstellungen.KEY_JOBID, Einstellungen.aktJob.getId());
                        startActivity(iSicherungIntent);
                        mAktivity.finish();
                    }
                });

                ihilfe.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(mCallbacks != null)
                            mCallbacks.onNavigationDrawerIconSelected(R.id.N_icon_hilfe);
                    }
                });
            }
        }

        private void bindViewCharts(View view){
            TextView mName = view.findViewById(R.id.N_allgemein_name);
            TextView mHint = view.findViewById(R.id.N_allgemein_hint_name);

            // werte setzen
            mName.setText(getString(R.string.charts));
            mHint.setText(getString(R.string.hint_charts));


            // Handler registrieren
        }

        private void bindViewStempel(View view){
            TextView mName = view.findViewById(R.id.N_allgemein_name);
            TextView mHint = view.findViewById(R.id.N_allgemein_hint_name);

            // werte setzen
            mName.setText(getString(R.string.stempeluhr));
            mHint.setText(getString(R.string.hint_stempeluhr));


            // Handler registrieren
        }


        private void bindViewFeiertage(View view){
            TextView mName = view.findViewById(R.id.N_allgemein_name);
            TextView mHint = view.findViewById(R.id.N_allgemein_hint_name);

            // werte setzen
            mName.setText(getString(R.string.feiertage));
            mHint.setText(getString(R.string.hint_feiertage));


            // Handler registrieren
        }
    }
}
