package com.hikapro.backpack.presenter;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SearchView;
import android.widget.Toast;

import com.hikapro.backpack.R;
import com.hikapro.backpack.model.Model;
import com.hikapro.backpack.model.entities.Category;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.presenter.adapters.AddListAdapter;
import com.hikapro.backpack.presenter.adapters.helper.FlowLayout;
import com.hikapro.backpack.presenter.adapters.helper.Util;
import com.hikapro.backpack.presenter.adapters.helper.items.DividerDecoration;
import com.hikapro.backpack.presenter.adapters.helper.items.DividerDecoration2;
import com.hikapro.backpack.view.View;

import java.lang.ref.WeakReference;

/**
 * Created by tariel on 18/05/16.
 */
public class AddPresenter implements Presenter.Add {

    private WeakReference<View.Add>     view;
    private Model.Add                   model;

    private AddListAdapter              adapter;
    private RecyclerView                recycler;
    private FlowLayout                   categoryContainer;
    private ViewGroup                   categoryContainerMain;
    private boolean                     isContainerAlreadyInitialised;
    private Item                        newItem;
    private Item                        selectedItem;
    private Button                      currentCategoryButton;
    private Button                      cancelButton;
    private Button                      saveButton;
    private SearchView                  searchView;
    private boolean                     canSave;


    public AddPresenter() {
        this.adapter = new AddListAdapter(this);
    }

    @Override
    public void setView(View.Add view) {
        this.view = new WeakReference<>(view);
    }

    @Override
    public void setModel(Model.Add model) {
        this.model = model;

    }

    @Override
    public Model.Add getModel() {
        return model;
    }

    @Override
    public void onDestroy(boolean isChangingConfiguration) {
        view = null;
        model.onDestroy(isChangingConfiguration);
        if ( !isChangingConfiguration ) {
            model = null;
        }
        isContainerAlreadyInitialised = false;
    }

    @Override
    public android.view.View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        android.view.View view = inflater.inflate(R.layout.fragment_add, container, false);
        model.executeQuery();
        LinearLayoutManager llm = new LinearLayoutManager(getActivityContext());
        recycler = (RecyclerView) view.findViewById(R.id.add_item_recycler);
        recycler.setLayoutManager(llm);
        recycler.setAdapter(adapter);
        recycler.setItemAnimator(new DefaultItemAnimator());
        //recycler.addItemDecoration(new DividerDecoration(getActivityContext()));
        recycler.addItemDecoration(new DividerDecoration2(getActivityContext(), R.drawable.divider2, Util.dp2px(getAppContext(), 16)));
        categoryContainer = (FlowLayout) view.findViewById(R.id.add_item_category_flow);
        //categoryContainer.setPaddings(Util.dp2px(getAppContext(), 15), Util.dp2px(getAppContext(), 15)); // TODO check here
        categoryContainerMain = (ViewGroup) view.findViewById(R.id.add_item_category_container);
        categoryContainerMain.setVisibility(android.view.View.GONE);
        recycler.setVisibility(android.view.View.GONE);

        Activity activity = (Activity) getActivityContext();
        if (activity != null) {
            ActionBar actionBar = activity.getActionBar();
            if (actionBar != null) {
                ViewGroup custActionBarView = (ViewGroup) inflater.inflate(R.layout.add_cust_actionbar, null);
                actionBar.setDisplayShowHomeEnabled(false);
                actionBar.setDisplayShowTitleEnabled(false);
                actionBar.setDisplayShowCustomEnabled(true);
                actionBar.setDisplayHomeAsUpEnabled(false);
                actionBar.setCustomView(custActionBarView);

                cancelButton    = (Button) custActionBarView.findViewById(R.id.action_add_cancel);
                saveButton      = (Button) custActionBarView.findViewById(R.id.action_add_save);
                android.view.View.OnClickListener listener = new ActionBarButtonClickListener();
                cancelButton.setOnClickListener(listener);
                saveButton.setOnClickListener(listener);
            }
        }

        searchView = (SearchView) view.findViewById(R.id.add_search);
        searchView.setIconified(false);
        searchView.setIconifiedByDefault(false);
        searchView.setQueryHint(getActivityContext().getResources().getString(R.string.search_hint_add));
        searchView.setSubmitButtonEnabled(false);
        searchView.setBottom(20);

        int magId = searchView.getContext().getResources().getIdentifier("android:id/search_mag_icon", null, null);
        ImageView magImage = (ImageView) searchView.findViewById(magId);
        magImage.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
        searchView.setMinimumHeight(40);
        searchView.setOnQueryTextListener(new SearchTextListener());

        return view;
    }

    @Override
    public Context getAppContext() {
        try {
            return getView().getAppContext();
        } catch (NullPointerException e) {
            return null;
        }
    }

    @Override
    public Context getActivityContext() {
        try {
            return getView().getActivityContext();
        } catch (NullPointerException e) {
            return null;
        }
    }

    @Override
    public void notifyDataSetChanged(boolean found) {
        adapter.notifyDataSetChanged();
        if (found) {
            categoryContainerMain.setVisibility(android.view.View.GONE);
            recycler.setVisibility(android.view.View.VISIBLE);
            currentCategoryButton = null;
        } else {
            categoryContainerMain.setVisibility(android.view.View.VISIBLE);
            recycler.setVisibility(android.view.View.GONE);
            initSelectCategoryContainer();
        }
    }

    @Override
    public void onAddItemClick(Item item) {
        searchView.setQuery(item.getName(), false);
        if (!item.InList)
            selectedItem = item;
        setSaveButtonAccess();
    }

    private void setSaveButtonAccess() {

        if (searchView.getQuery().length() > 0 && currentCategoryButton != null
                || selectedItem != null)
            canSave = true;
        else
            canSave = false;

        if (canSave)
            saveButton.setTextColor(saveButton.getResources().getColor(R.color.save_green));
        else
            saveButton.setTextColor(saveButton.getResources().getColor(R.color.white));
    }

    private boolean checkUserInput() {
        if (!canSave) {
            if (searchView.getQuery().length() == 0)
                Toast.makeText(getActivityContext(), R.string.enter_name, Toast.LENGTH_SHORT).show();
            else if (categoryContainerMain.getVisibility() == android.view.View.VISIBLE)
                Toast.makeText(getActivityContext(), R.string.select_category, Toast.LENGTH_SHORT).show();
            else
                Toast.makeText(getActivityContext(), R.string.already_in_list2, Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void initSelectCategoryContainer() {
        Button button;
        Category category;
        if (! isContainerAlreadyInitialised) {

            for (int i = 0; i < model.getCategoriesCount(); ++i) {
                category = model.getCategoryByPosition(i);
                button = (Button) LayoutInflater.from(getActivityContext()).inflate(
                        R.layout.category_button, null);
                button.setId(category.getId());
                String txt = category.getName();

                button.setText(txt);
                button.setOnClickListener(new CategoryButtonClickListener());
                categoryContainer.addView(button);

                if (currentCategoryButton != null) {
                    if (button.getId() == currentCategoryButton.getId()) {
                        currentCategoryButton = button;
                        Drawable d = currentCategoryButton.getBackground();
                        PorterDuffColorFilter filter = new PorterDuffColorFilter(Color.GREEN, PorterDuff.Mode.SRC_ATOP);
                        d.setColorFilter(filter);
                    }
                }
            }
            setSaveButtonAccess();
            isContainerAlreadyInitialised = true;
        }
    }

    private View.Add getView() throws NullPointerException {
        if ( view != null )
            return view.get();
        else
            throw new NullPointerException("View is unavailable");
    }

    private class CategoryButtonClickListener implements android.view.View.OnClickListener {
        @Override
        public void onClick(android.view.View v) {

            Drawable d = v.getBackground();
            PorterDuffColorFilter filter = new PorterDuffColorFilter(Color.GREEN, PorterDuff.Mode.SRC_ATOP);
            d.setColorFilter(filter);

            if (currentCategoryButton != null) {
                d = currentCategoryButton.getBackground();
                currentCategoryButton.invalidateDrawable(d);
                d.clearColorFilter();
            }

            currentCategoryButton = (Button) v;
            setSaveButtonAccess();
        }
    }

    private class ActionBarButtonClickListener implements android.view.View.OnClickListener {
        @Override
        public void onClick(android.view.View v) {
            Fragment fragment = (Fragment) getView();
            switch (v.getId())
            {
                case R.id.action_add_cancel :
                    searchView.clearFocus();
                    if (fragment != null)
                        fragment.getFragmentManager().popBackStack();
                    break;

                case R.id.action_add_save :
                    if (checkUserInput()) {
                        if (selectedItem != null) {
                            model.add(selectedItem, getView().getSet().getId());
                        } else {
                            newItem = new Item(searchView.getQuery().toString(), currentCategoryButton.getId());
                            newItem.setUserDefined(true);
                            model.add(newItem, getView().getSet().getId());
                        }
                        searchView.clearFocus();
                        if (fragment != null)
                            fragment.getFragmentManager().popBackStack();
                    }
                    break;
            }
        }
    }

    private class SearchTextListener implements SearchView.OnQueryTextListener {

        public SearchTextListener() {
            super();
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            model.filter(newText, getView().getSet().getId());
            if (newText.isEmpty()) {
                if (currentCategoryButton != null) {
                    Drawable d = currentCategoryButton.getBackground();
                    currentCategoryButton.invalidateDrawable(d);
                    d.clearColorFilter();
                    currentCategoryButton = null;
                }
            }
            selectedItem = null;
            setSaveButtonAccess();
            return true;
        }

        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }
    }
}
