package com.gpshopper.platform.fragment;

import android.app.Fragment;
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.gpshopper.platform.App;
import com.gpshopper.platform.R;
import com.gpshopper.sdk.catalog.CatalogManager;
import com.gpshopper.sdk.catalog.request.category.CategoriesResponse;
import com.gpshopper.sdk.catalog.request.category.Category;
import com.gpshopper.sdk.network.model.SdkRequestCallback;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jc on 2/22/15.
 */
public class BrowseFragment extends BaseFragment {

    public static final String CATEGORY_ARG_KEY = "Category";
    public static final String BREADCRUMBS_ARG_KEY = "Breadcrumbs";

    private List<Category> categoryList;
    private String title;
    private String breadcrumbs;

    private ListView view;

    public static BrowseFragment newInstance() {
        return new BrowseFragment();
    }

    @Override
    public int getTitle() {
        return R.string.section_shop_browse;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_browse;
    }

    @Override
    public int getMenuId() {
        return R.menu.browse;
    }

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

        final Bundle arguments = getArguments();
        if (arguments != null) {
            final Category category = arguments.getParcelable(CATEGORY_ARG_KEY);
            categoryList = category.getChildList();
            title = category.getTitle();
            breadcrumbs = arguments.getString(BREADCRUMBS_ARG_KEY);
            App.sendTracking("Browse", breadcrumbs == null ? title : breadcrumbs);
        } else {
            App.sendTracking("Browse");
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = (ListView) super.onCreateView(inflater, container, savedInstanceState);

        view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final Category category = categoryList.get(position);
                final List<Category> childList = category.getChildList();
                if (childList == null || childList.isEmpty()) {
                    if (category.getQuery() == null) {
                        return;
                    }
                    final Fragment fragment = ProductsFragment.newInstance();
                    final Bundle arguments = new Bundle();
                    arguments.putString(ProductsFragment.QUERY_ARG_KEY, category.getQuery());
                    arguments.putString(ProductsFragment.TITLE_ARG_KEY, category.getTitle());
                    arguments.putString(ProductsFragment.BREADCRUMBS_ARG_KEY, title + (breadcrumbs != null ? " / " + breadcrumbs : ""));
                    fragment.setArguments(arguments);
                    showFragment(fragment);
                } else {
                    final Fragment fragment = BrowseFragment.newInstance();
                    final Bundle arguments = new Bundle();
                    arguments.putParcelable(CATEGORY_ARG_KEY, category);
                    arguments.putString(BREADCRUMBS_ARG_KEY, breadcrumbs);
                    fragment.setArguments(arguments);
                    showFragment(fragment);
                }
            }
        });

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();

        if (title != null && !title.isEmpty()) {
            setTitle(title);
        }

        if (categoryList == null || categoryList.isEmpty()) {
            request();
        }

        populate();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
        final MenuItem searchItem = menu.findItem(R.id.action_search);
        if (searchItem != null) {
            final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

            searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
                    searchView.clearFocus();

                    final Fragment fragment = ProductsFragment.newInstance();
                    final Bundle arguments = new Bundle();
                    arguments.putString(ProductsFragment.QUERY_ARG_KEY, query);
                    arguments.putString(ProductsFragment.TITLE_ARG_KEY, query);
                    fragment.setArguments(arguments);
                    showFragment(fragment);

                    return true;
                }

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

        super.onCreateOptionsMenu(menu, inflater);
    }

    private void request() {
        CatalogManager.getInstance().fetchCategories(new SdkRequestCallback<CategoriesResponse>() {
            @Override
            public void onComplete(CategoriesResponse categoriesResponse) {
                categoryList = categoriesResponse.getCategories();

                populate();
            }

            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onError(int i, String s, Exception e) {

            }

            @Override
            public void onFatalError(Exception e) {

            }
        });
    }

    private void populate() {
        if (getView() == null || categoryList == null || categoryList.isEmpty()) {
            return;
        }

        List<String> titles = new ArrayList<>();
        for (Category category : categoryList) {
            titles.add(category.getTitle());
        }

        ArrayAdapter<String> categoryAdapter = new ArrayAdapter<>(getActivity(), R.layout.item_browse, titles);
        view.setAdapter(categoryAdapter);
    }
}
