package com.droideve.apps.dealify.navigationdrawer;


import android.annotation.SuppressLint;
import androidx.fragment.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.droideve.apps.dealify.AppController;
import com.droideve.apps.dealify.R;
import com.droideve.apps.dealify.activities.AboutActivity;
import com.droideve.apps.dealify.activities.DeliveryAnalytics;
import com.droideve.apps.dealify.activities.LoginV2Activity;
import com.droideve.apps.dealify.activities.ProfileActivity;
import com.droideve.apps.dealify.activities.SettingActivity;
import com.droideve.apps.dealify.activities.SplashActivity;
import com.droideve.apps.dealify.activities.WalletActivity;
import com.droideve.apps.dealify.adapter.navigation.SimpleListAdapterNavDrawer;
import com.droideve.apps.dealify.classes.HeaderItem;
import com.droideve.apps.dealify.classes.ItemNav;
import com.droideve.apps.dealify.controllers.SettingsController;
import com.droideve.apps.dealify.controllers.sessions.SessionsController;
import com.droideve.apps.dealify.fragments.MainFragment;
import com.mikepenz.community_material_typeface_library.CommunityMaterial;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;


public class NavigationDrawerFragment extends Fragment implements SimpleListAdapterNavDrawer.ClickListener {


    public static final String PREF_FILE_NAME = "testpref";
    public static final String KEY_USER_LEARNED_DRAWER = "learned_user_drawer";
    public static int INT_CHAT_BOX = 5;
    private static DrawerLayout mDrawerLayout;
    List<ItemNav> listItemNavs = Collections.emptyList();
    private ActionBarDrawerToggle mActionBarDrawerToggle;
    private boolean mUserLearedLayout;
    private boolean mFromSaveInstanceState;


    //init request http
    private SimpleListAdapterNavDrawer adapter;

    public static DrawerLayout getInstance() {
        return mDrawerLayout;
    }

    public static void saveToPreferences(Context context, String preferenceName, String preferenceValue) {

        SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString(preferenceName, preferenceValue);
        edit.apply();

    }

    public static String readFromPreferences(Context context, String preferenceName, String defaultValue) {

        SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getString(preferenceName, defaultValue);

    }

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


        mUserLearedLayout = Boolean.valueOf(readFromPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, "false"));
        if (savedInstanceState != null) {
            mFromSaveInstanceState = true;
        }


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.navigation_drawer_content, container, false);

        rootView.setClickable(true);

        RecyclerView drawerList = rootView.findViewById(R.id.drawerLayout);
        drawerList.setVisibility(View.VISIBLE);

        adapter = new SimpleListAdapterNavDrawer(getActivity(), getData());

        drawerList.setHasFixedSize(true);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        drawerList.setLayoutManager(mLayoutManager);
        drawerList.setAdapter(adapter);

        adapter.setClickListener(this);

        return rootView;

    }


    public List<ItemNav> getData() {

        listItemNavs = new ArrayList<ItemNav>();


        HeaderItem header_item = new HeaderItem();
        header_item.setName(AppController.getInstance().getResources().getString(R.string.Home));
        header_item.setEnabled(true);

        ItemNav homeItemNav = new ItemNav();
        homeItemNav.setName(getResources().getString(R.string.Home));
        homeItemNav.setIconDraw(CommunityMaterial.Icon2.cmd_home_outline);
        homeItemNav.setID(Menu.HOME);


        ItemNav aboutItemNav = new ItemNav();
        aboutItemNav.setName(AppController.getInstance().getResources().getString(R.string.about));
        aboutItemNav.setIconDraw(CommunityMaterial.Icon2.cmd_information_outline);
        aboutItemNav.setID(Menu.ABOUT);


        ItemNav settingItemNav = new ItemNav();
        settingItemNav.setName(AppController.getInstance().getResources().getString(R.string.Settings));
        settingItemNav.setImageId(R.drawable.ic_cog_outline);
        settingItemNav.setID(Menu.SETTING);


        ItemNav editProdile = new ItemNav();
        editProdile.setName(AppController.getInstance().getResources().getString(R.string.editProfile));
        editProdile.setIconDraw(CommunityMaterial.Icon.cmd_account_outline);
        editProdile.setID(Menu.EDIT);


        ItemNav logout = new ItemNav();
        logout.setName(AppController.getInstance().getResources().getString(R.string.Logout));
        logout.setIconDraw(CommunityMaterial.Icon.cmd_exit_to_app);
        logout.setID(Menu.LOGOUT);


        if (header_item.isEnabled())
            listItemNavs.add(header_item);


        //d wallet
        if (SettingsController.isModuleEnabled("digital_wallet")) {
            ItemNav itemW = new ItemNav();
            itemW.setName(getResources().getString(R.string.MyWallet));
            //itemW.setIconDraw(CommunityMaterial.Icon2.cmd_wallet);
            itemW.setImageId(R.drawable.ic_ic_wallet);
            itemW.setID(Menu.DIGITAL_WALLET);
            if (itemW.isEnabled())
                listItemNavs.add(itemW);
        }

        //Edit Profile
        if (editProdile.isEnabled() && SessionsController.isLogged())
            listItemNavs.add(editProdile);


        //logout
        if (logout.isEnabled() && SessionsController.isLogged())
            listItemNavs.add(logout);

        //Settings
        if (settingItemNav.isEnabled())
            listItemNavs.add(settingItemNav);

        //About US
        if (aboutItemNav.isEnabled())
            listItemNavs.add(aboutItemNav);


        return listItemNavs;
    }

    public void setUp(int FragId, DrawerLayout drawerlayout, final Toolbar toolbar) {

        View containerView = Objects.requireNonNull(getView()).findViewById(FragId);
        mDrawerLayout = drawerlayout;

        //mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);

        mActionBarDrawerToggle = new ActionBarDrawerToggle(
                getActivity(),
                drawerlayout,
                toolbar,
                R.string.drawer_open,
                R.string.drawer_close
        ) {
            @Override
            public void onDrawerOpened(View drawerView) {

                super.onDrawerOpened(drawerView);
                if (!mUserLearedLayout) {
                    mUserLearedLayout = true;
                    saveToPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, mUserLearedLayout + "");
                }


                getActivity().invalidateOptionsMenu();

            }

            @Override
            public void onDrawerClosed(View drawerView) {

                super.onDrawerClosed(drawerView);
                getActivity().invalidateOptionsMenu();

            }


            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                super.onDrawerSlide(drawerView, slideOffset);

            }
        };

        if (!mUserLearedLayout && !mFromSaveInstanceState) {
            mDrawerLayout.closeDrawer(containerView);
        }


        mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
        mDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
                mActionBarDrawerToggle.syncState();

            }
        });

    }


    @Override
    public void onStart() {
        //EventBus.getDefault().register(this);


        super.onStart();

    }

    @Override
    public void onPause() {
        super.onPause();
        //EventBus.getDefault().unregister(this);
    }


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

        if (requestCode == INT_CHAT_BOX) {

            adapter.getData().get(1).setNotify(0);
            adapter.update(1, adapter.getData().get(1));

        }
    }


    @SuppressLint("ResourceAsColor")
    @Override
    public void itemClicked(View view, int position) {

        MainFragment mf = (MainFragment) getFragmentManager().findFragmentByTag(MainFragment.TAG);

        ItemNav ItemNav = adapter.getData().get(position);
        if (ItemNav != null) {
            switch (ItemNav.getID()) {
                case Menu.HOME:
                    if (mDrawerLayout != null)
                        mDrawerLayout.closeDrawers();

                    mf.setCurrentFragment(0);

                    break;
                case Menu.DIGITAL_WALLET:
                    if (SessionsController.isLogged()) {
                        Intent intent = new Intent(getActivity(), WalletActivity.class);
                        startActivity(intent);
                    } else {
                        startActivity(new Intent(getActivity(), LoginV2Activity.class));
                    }
                    break;
                case Menu.CHAT_LOGIN_ID:
                    if (!SessionsController.isLogged()) {
                        startActivity(new Intent(getActivity(), LoginV2Activity.class));
                    }
                    break;
                case Menu.EDIT:

                    if (mDrawerLayout != null)
                        mDrawerLayout.closeDrawers();

                    startActivity(new Intent(getActivity(), ProfileActivity.class));
                    break;
                case Menu.ABOUT:

                    if (mDrawerLayout != null)
                        mDrawerLayout.closeDrawers();

                    startActivity(new Intent(getActivity(), AboutActivity.class));
                    getActivity().overridePendingTransition(R.anim.lefttoright_enter, R.anim.lefttoright_exit);

                    break;

                case Menu.SETTING:

                    if (mDrawerLayout != null)
                        mDrawerLayout.closeDrawers();

                    startActivity(new Intent(getActivity(), SettingActivity.class));
                    getActivity().overridePendingTransition(R.anim.lefttoright_enter, R.anim.lefttoright_exit);

                    break;
                case Menu.LOGOUT:

                    SessionsController.logOut();
                    getActivity().finish();
                    startActivity(new Intent(getActivity(), SplashActivity.class));

                    break;


            }
        }


    }

    private static class Menu {
        public static final int HOME = 1;
        static final int CHAT_LOGIN_ID = 4;
        static final int EDIT = 7;
        static final int ABOUT = 8;
        static final int SETTING = 10;
        static final int LOGOUT = 11;

        static final int DIGITAL_WALLET = 18;


    }


}
