package com.droideve.apps.dealify.navigationdrawer;


import android.annotation.SuppressLint;
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 android.webkit.CookieManager;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.res.ResourcesCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
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.Services.BusStation;
import com.droideve.apps.dealify.activities.AboutActivity;
import com.droideve.apps.dealify.activities.BookmarkActivity;
import com.droideve.apps.dealify.activities.CategoriesActivity;
import com.droideve.apps.dealify.activities.InboxActivity;
import com.droideve.apps.dealify.activities.ListDiscussionsActivity;
import com.droideve.apps.dealify.activities.ListOrdersActivity;
import com.droideve.apps.dealify.activities.ListUsersActivity;
import com.droideve.apps.dealify.activities.LoginV2Activity;
import com.droideve.apps.dealify.activities.MapStoresListActivity;
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.appconfig.AppConfig;
import com.droideve.apps.dealify.appconfig.Constances;
import com.droideve.apps.dealify.classes.HeaderItem;
import com.droideve.apps.dealify.classes.Item;
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.google.android.material.badge.BadgeUtils;
import com.mikepenz.community_material_typeface_library.CommunityMaterial;
import com.mikepenz.fontawesome_typeface_library.FontAwesome;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.wuadam.awesomewebview.AwesomeWebView;

import org.greenrobot.eventbus.Subscribe;

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


public class NavigationDrawerFragment extends Fragment implements SimpleListAdapterNavDrawer.ClickListener {


    //save instance of Navigation State
    public final static String PREF_FILE_NAME = "testpref";
    public final static String KEY_USER_LEARNED_DRAWER = "learned_user_drawer";

    //code of chat box
    public int INT_CHAT_BOX = 5;

    //navigation drawer
    private static DrawerLayout mDrawerLayout;

    //list items
    private List<ItemNav> listItemNavs = Arrays.asList();

    //action bar
    private ActionBarDrawerToggle mActionBarDrawerToggle;

    //other variables
    private boolean mUserLearedLayout;
    private boolean mFromSaveInstanceState;
    private View containerView;

    //Receycler view (list view)
    private RecyclerView drawerList;

    //init adapter
    private SimpleListAdapterNavDrawer adapter;

    public static DrawerLayout getInstance() {
        return mDrawerLayout;
    }

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

        SharedPreferences sharedPreferences = context.getSharedPreferences(NavigationDrawerFragment.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(NavigationDrawerFragment.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(getResources().getString(R.string.Home));
        header_item.setEnabled(true);
        if (header_item.isEnabled())
            listItemNavs.add(header_item);

        //HOME
        ItemNav homeItem = new ItemNav();
        homeItem.setName(getResources().getString(R.string.Home));
        homeItem.setIconDraw(CommunityMaterial.Icon2.cmd_home_outline);
        homeItem.setID(Menu.HOME_ID);
        if (homeItem.isEnabled())
            listItemNavs.add(homeItem);


        //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);
        }

        //GEO Stores
        ItemNav mapStoresItem = new ItemNav();
        mapStoresItem.setName(getResources().getString(R.string.MapStoresMenu));
        mapStoresItem.setIconDraw(CommunityMaterial.Icon2.cmd_map_outline);
        mapStoresItem.setID(Menu.MAP_STORES);
        listItemNavs.add(mapStoresItem);



        //Booking
        if (SettingsController.isModuleEnabled("nsorder")) {
            ItemNav bookingItem = new ItemNav();
            bookingItem.setName(getResources().getString(R.string.orders));
            bookingItem.setIconDraw(CommunityMaterial.Icon.cmd_cart_outline);
            bookingItem.setID(Menu.ORDERS);
            if (bookingItem.isEnabled())
                listItemNavs.add(bookingItem);
        }

        //business manager
        if (SettingsController.isModuleEnabled("business_manager")) {
            ItemNav webdashboard = new ItemNav();
            webdashboard.setName(getResources().getString(R.string.ManageThings));
            webdashboard.setIconDraw(CommunityMaterial.Icon.cmd_briefcase_outline);
            webdashboard.setID(Menu.MANAGE_YOUR_BUSINESS);
            listItemNavs.add(webdashboard);
        }

        //Account
        ItemNav logout = new ItemNav();
        logout.setName(getResources().getString(R.string.my_account));
        logout.setIconDraw(CommunityMaterial.Icon.cmd_account_outline);
        logout.setID(Menu.ACCOUNT);
        listItemNavs.add(logout);


        ItemNav inbox = new ItemNav();
        inbox.setName(getResources().getString(R.string.inbox));
        inbox.setIconDraw(CommunityMaterial.Icon2.cmd_inbox);
        inbox.setID(Menu.INBOX);
        listItemNavs.add(inbox);


        //About US
        ItemNav aboutItem = new ItemNav();
        aboutItem.setName(getResources().getString(R.string.about));
        aboutItem.setIconDraw(CommunityMaterial.Icon2.cmd_information_outline);
        aboutItem.setID(Menu.ABOUT);

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

        //Settings
        ItemNav settingItem = new ItemNav();
        settingItem.setName(getResources().getString(R.string.Settings));
        settingItem.setIconDraw(CommunityMaterial.Icon2.cmd_settings_outline);
        settingItem.setID(Menu.SETTING);
        if (settingItem.isEnabled())
            listItemNavs.add(settingItem);

        return listItemNavs;
    }


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

        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 + "");
                }
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }


            @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() {
        super.onStart();
    }


    @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 item = adapter.getData().get(position);
        if (item != null) {

            switch (item.getID()) {
                case Menu.HOME_ID:
                    MainFragment mf = (MainFragment) getFragmentManager().findFragmentByTag(MainFragment.TAG);
                    mf.setCurrentFragment(0);
                    break;
                case Menu.MANAGE_YOUR_BUSINESS:
                   /* Intent intent = new Intent(getActivity(), BusinessManagerWebViewActivity.class);
                    startActivity(intent);*/
                    break;
                case Menu.ORDERS:
                    if (SessionsController.isLogged()) {
                        Intent bookingIntent = new Intent(getActivity(), ListOrdersActivity.class);
                        startActivity(bookingIntent);
                    } else {
                        startActivity(new Intent(getActivity(), LoginV2Activity.class));
                    }
                    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.ABOUT:
                    startActivity(new Intent(getActivity(), AboutActivity.class));
                    break;
                case Menu.SETTING:
                    startActivity(new Intent(getActivity(), SettingActivity.class));
                    break;
                case Menu.MAP_STORES:
                    startActivity(new Intent(getActivity(), MapStoresListActivity.class));
                    break;
                case Menu.ACCOUNT:
                    if(SessionsController.isLogged()){
                        startActivity(new Intent(getActivity(), ProfileActivity.class));
                    }else{
                        startActivity(new Intent(getActivity(), LoginV2Activity.class));
                    }
                    break;
                case Menu.INBOX:
                    if(SessionsController.isLogged()){
                        startActivity(new Intent(getActivity(), ListDiscussionsActivity.class));
                    }else{
                        startActivity(new Intent(getActivity(), LoginV2Activity.class));
                    }
                    break;
            }

        }


    }

    @Override
    public void onResume() {
        super.onResume();
        BusStation.getBus().register(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        BusStation.getBus().unregister(this);
    }

    @Subscribe
    public void onToggle(NavigationDrawerEvent object) {
        if (object.state == 1) {
            if (mDrawerLayout.isDrawerOpen(containerView))
                mDrawerLayout.closeDrawer(containerView);
            else
                mDrawerLayout.openDrawer(containerView);
        }
    }

    private static class Menu {
        public static final int INBOX = 1223;
        static final int ACCOUNT = 122;
        static final int HOME_ID = 1;
        static final int CAT_ID = 2;
        static final int PEOPLE_AROUND_ME = 3;
        static final int CHAT_LOGIN_ID = 4;
        static final int NOTIFICATIONS = 5;
        static final int EDIT = 7;
        static final int ABOUT = 8;
        static final int CREATE_STORE = 9;
        static final int SETTING = 10;
        static final int LOGOUT = 11;
        static final int WEB_DASHBOARD = 12;
        static final int MAP_STORES = 13;
        static final int FAV = 14;
        static final int ORDERS = 15;

        static final int MANAGE_YOUR_BUSINESS = 16;
        static final int DIGITAL_WALLET = 17;

    }

    public static class NavigationDrawerEvent {
        private int state = 0;

        public NavigationDrawerEvent(int state) {
            this.state = state;
        }
    }

}
