package it.integry.integrywmsnative;

import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import com.google.android.material.navigation.NavigationView;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;

import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import it.integry.integrywmsnative.core.REST.watcher.ServerStatusChecker;
import it.integry.integrywmsnative.core.barcode_reader.BarcodeManager;
import it.integry.integrywmsnative.core.interfaces.IFilterableFragment;
import it.integry.integrywmsnative.core.interfaces.IRecyclerFragment;
import it.integry.integrywmsnative.core.interfaces.ISelectAllFragment;
import it.integry.integrywmsnative.core.settings.SettingsManager;
import it.integry.integrywmsnative.core.update.UpdatesManager;
import it.integry.integrywmsnative.core.utility.UtilitySettings;
import it.integry.integrywmsnative.databinding.ActivityMainBinding;
import it.integry.integrywmsnative.gest.accettazione.MainAccettazioneFragment;
import it.integry.integrywmsnative.core.interfaces.ITitledFragment;
import it.integry.integrywmsnative.gest.login.LoginActivity;
import it.integry.integrywmsnative.gest.main.MainFragment;
import it.integry.integrywmsnative.gest.rettifica_giacenze.RettificaGiacenzeFragment;
import it.integry.integrywmsnative.gest.settings.MainSettingsFragment;
import it.integry.integrywmsnative.gest.vendita.MainVenditaFragment;
import it.integry.integrywmsnative.gest.versamento_merce.VersamentoMerceFragment;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private ActivityMainBinding mBinding;

    private boolean firstCheckExecution = true;
    private boolean mIsOnline = false;

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



        mBinding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.activity_main, null, false);
        setContentView(mBinding.getRoot());

        UpdatesManager.init(this);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, mBinding.drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        mBinding.drawerLayout.setDrawerListener(toggle);
        toggle.syncState();


        mBinding.navView.setNavigationItemSelectedListener(this);
        mBinding.appBarMain.mainSearch.setVisibility(View.GONE);

        changeContentFragment(MainFragment.newInstance());

        init();
    }


    private void startLoginActivity(){
        this.finish();
        Intent myIntent = new Intent(this, LoginActivity.class);
        startActivity(myIntent);
    }



    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, 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();

        //noinspection SimplifiableIfStatement
//        if (id == R.id.action_search) {
//            return true;
//        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {

        mBinding.appBarMain.waterfallToolbar.resetElevation();
        mBinding.appBarMain.waterfallToolbar.setRecyclerView(null);

        // Handle navigation view item clicks here.
        Fragment fragment = null;
        int id = item.getItemId();

        if (id == R.id.nav_accettazione) {
            fragment = MainAccettazioneFragment.newInstance();
            this.adaptViewToFragment(fragment);
        } else if (id == R.id.nav_gallery) {
            fragment = MainVenditaFragment.newInstance();
            this.adaptViewToFragment(fragment);
        } else if (id == R.id.nav_slideshow) {
            fragment = RettificaGiacenzeFragment.newInstance();
            this.adaptViewToFragment(fragment);
        } else if (id == R.id.nav_manage) {
            fragment = VersamentoMerceFragment.newInstance();
            this.adaptViewToFragment(fragment);
        }
        /*else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }*/


        else if(id == R.id.nav_settings){
            fragment = new MainSettingsFragment();
            this.adaptViewToFragment(fragment);
        }

        else if(id == R.id.nav_logout){
            UtilitySettings.logout();
            startLoginActivity();
        }

        changeContentFragment(fragment);

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void popToMain() {
        MainFragment mainFragment = MainFragment.newInstance();

        adaptViewToFragment(mainFragment);

        changeContentFragment(mainFragment);
    }

    private void adaptViewToFragment(Fragment fragment){
        if(fragment instanceof SearchView.OnQueryTextListener) {
            mBinding.appBarMain.mainSearch.setOnQueryTextListener((SearchView.OnQueryTextListener) fragment);
            mBinding.appBarMain.mainSearch.setVisibility(View.VISIBLE);
        } else {
            mBinding.appBarMain.mainSearch.setOnQueryTextListener(null);
            mBinding.appBarMain.mainSearch.setVisibility(View.GONE);
        }


        if(fragment instanceof ITitledFragment) {
            getSupportActionBar().setTitle(((ITitledFragment) fragment).getTitle(this));
        } else {
            getSupportActionBar().setTitle(R.string.app_name);
        }

        if(fragment instanceof IRecyclerFragment) {
            ((IRecyclerFragment) fragment).setWaterfallToolbar(mBinding.appBarMain.waterfallToolbar);
        }

        if(fragment instanceof ISelectAllFragment && ((ISelectAllFragment)fragment).isEnabled()) {
            mBinding.appBarMain.mainSelectAll.setVisibility(View.VISIBLE);
            mBinding.appBarMain.mainSelectAll.setOnClickListener(v -> ((ISelectAllFragment)fragment).onSelectAll());
        } else {
            mBinding.appBarMain.mainSelectAll.setVisibility(View.GONE);
            mBinding.appBarMain.mainSelectAll.setOnClickListener(null);
        }

        if(fragment instanceof IFilterableFragment) {
            mBinding.appBarMain.mainFilter.setVisibility(View.VISIBLE);
            mBinding.appBarMain.mainFilter.setOnClickListener(v -> ((IFilterableFragment)fragment).onFilterClick());
        } else {
            mBinding.appBarMain.mainFilter.setVisibility(View.GONE);
            mBinding.appBarMain.mainFilter.setOnClickListener(null);
        }
    }

    private void changeContentFragment(Fragment fragment){
        if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit();

        }
    }






    private void init(){

        if(BarcodeManager.getCurrentBarcodeInterface() != null) {
//            DialogSimpleMessageHelper.makeInfoDialog(this,
//                    "Lettore barcode",
//                    new SpannableString("Trovato adattatore " + BarcodeManager.getCurrentBarcodeInterface().getAdapterName() + " installato nel sistema"),
//                    null, null).show();
        }
        //Preload done in splashPage
        onDBLoaded();

        ServerStatusChecker.getIstance().addCallback(value -> {
            if(value && (!mIsOnline || firstCheckExecution)){

                SettingsManager.reloadDBVariables(() -> {
                        mIsOnline = true;
                        firstCheckExecution = false;

                        onDBLoaded();
                    }, ex -> {
                        //mNoConnectionLayout.expand(true);
                        if(!mIsOnline) mIsOnline = false;
                    }
                );

            } else if(!value && mIsOnline){
                mIsOnline = false;
            }
        });

    }


    private void onDBLoaded() {
        LinearLayout headerLayout = (LinearLayout) mBinding.navView.getHeaderView(0);

        ((TextView) headerLayout.findViewById(R.id.drawer_username)).setText(SettingsManager.i().user.fullname);
        ((TextView) headerLayout.findViewById(R.id.drawer_deposito)).setText(SettingsManager.i().userSession.depo.getCodMdep() + " - " + SettingsManager.i().userSession.depo.getDescrizione());

        if(SettingsManager.iDB().getDatiAzienda() != null && SettingsManager.iDB().getDatiAzienda().isLogoAvailable()) {
            ((ImageView) headerLayout.findViewById(R.id.drawer_logoAzienda)).setImageBitmap(SettingsManager.iDB().getDatiAzienda().getLogo());
        }
    }

}
