package com.hikapro.backpack.presenter;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.ref.WeakReference;

import com.hikapro.backpack.R;
import com.hikapro.backpack.model.Model;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.model.entities.Set;
import com.hikapro.backpack.presenter.adapters.helper.Util;
import com.hikapro.backpack.presenter.adapters.helper.items.DividerDecoration;
import com.hikapro.backpack.presenter.adapters.ItemListAdapter;
import com.hikapro.backpack.presenter.adapters.helper.items.DividerDecoration2;
import com.hikapro.backpack.presenter.adapters.helper.items.ItemSwipeCallback;
import com.hikapro.backpack.presenter.adapters.helper.items.StickyHeaderDecoration;
import com.hikapro.backpack.view.View;

/**
 * Created by tariel on 20/04/16.
 */
public class ItemListPresenter implements Presenter.ItemList {

    protected static final String BUNDLE_SET_LIST_KEY = "BUNDLE_SET_LIST_KEY";

    protected WeakReference<View.ItemList>  view;
    protected Model.Item                    model;
    protected Set                           set;
    protected ItemListAdapter               adapter;
    protected RecyclerView                  recycler;

    private LinearLayout                    footer;
    private TextView                        showPacked;
    protected TextView                      packedCount;

    public ItemListPresenter() {
        this.adapter = new ItemListAdapter(this);
        adapter.setHasStableIds(true);
    }

    // life cycle -->

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

    @Override
    public android.view.View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO check nn
        if (savedInstanceState != null)
            set = (Set) savedInstanceState.getSerializable(BUNDLE_SET_LIST_KEY);
        else
            set = getView().getSet();
        android.view.View view = inflater.inflate(R.layout.fragment_item_list, container, false);
        LinearLayoutManager llm = new LinearLayoutManager(getActivityContext());
        recycler = (RecyclerView) view.findViewById(R.id.items_recycler);
        recycler.setLayoutManager(llm);
        recycler.setAdapter(adapter);

        final StickyHeaderDecoration decoration = new StickyHeaderDecoration(adapter);
        recycler.addItemDecoration(decoration);
        //recycler.addItemDecoration(new DividerDecoration(getActivityContext()));
        recycler.addItemDecoration(new DividerDecoration2(getActivityContext(), R.drawable.divider, Util.dp2px(getAppContext(), 16)));

        adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                decoration.invalidateHeaders();
            }
        });
        recycler.setHasFixedSize(true);
        model.executeQuery();
        footer      = (LinearLayout) view.findViewById(R.id.item_list_footer);
        packedCount = (TextView) footer.findViewById(R.id.footer_packed_count);
        showPacked  = (TextView) footer.findViewById(R.id.open_packed);
        showPacked.setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(android.view.View v) {
                showPackedItems();
            }
        });
        Activity activity = (Activity) getActivityContext();
        if (activity != null) {
            activity.invalidateOptionsMenu();
            ActionBar actionBar = activity.getActionBar();
            if (actionBar != null) {
                actionBar.show();
                actionBar.setTitle(set.getName());
                actionBar.setDisplayShowHomeEnabled(false);
                actionBar.setDisplayShowTitleEnabled(true);
                actionBar.setDisplayShowCustomEnabled(false);
                actionBar.setDisplayHomeAsUpEnabled(true);
            }
        }

        return view;
    }
    @Override
    public void onSaveInstanceState(Bundle outState) {
        if (set != null)
            outState.putSerializable(BUNDLE_SET_LIST_KEY, set);
    }

    // life cycle <--

    // process -->

    @Override
    public void notifyDataSetChanged() {
        adapter.notifyDataSetChanged();
    }

    @Override
    public void notifyItemPackStatusChanged() {

        setVisibility();
        Context context = getActivityContext();
        if (context != null) {

            String str = String.format("%s %d / %d",
                    context.getResources().getString(R.string.packed),
                    model.getPackedQty(),
                    model.getActiveItemsCount());
            packedCount.setText(str);
        }
    }

    @Override
    public void setVisibility() {
        if (model.getPackedQty() > 0 && model.getPackedQty() == model.getActiveItemsCount()) {
            footer.setVisibility(android.view.View.VISIBLE);
        } else if ( model.getPackedQty() > 0) {
            footer.setVisibility(android.view.View.VISIBLE);
        } else {
            footer.setVisibility(android.view.View.GONE);
        }

    }

    private void showPackedItems () {
        getView().showPackedItems(set);
    }

    @Override
    public void showDetails(int position) {
        getView().showItemDetail(getCurrentSet().getId(), model, position);
    }
    // process <--

    // other impl -->

    @Override
    public void setView(View.ItemList view) {
        this.view = new WeakReference<>(view);
        this.set = getView().getSet();
    }

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

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

    @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 showMessage(String message) {
        Toast.makeText(getView().getAppContext(), message, Toast.LENGTH_SHORT).show();
    }

    // other impl <--

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

    @Override
    public void filter(String query) {
        adapter.filter(query);
        recycler.scrollToPosition(0);
    }

    @Override
    public Set getCurrentSet() {
        return set;
    }

    @Override
    public void unpack(int setId) {
        model.unpackSet(setId);
    }

    @Override
    public void restore(final int setId) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivityContext(), AlertDialog.THEME_HOLO_DARK);

        builder.setMessage(R.string.dlg_restore_txt)
                .setTitle(R.string.dlg_restore_header);

        builder.setPositiveButton(R.string.ok_button, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                model.restoreSet(setId);
            }
        });
        builder.setNegativeButton(R.string.cancel_button, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User cancelled the dialog
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();

        //Button button = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
        //button.setBackgroundColor(Color.GREEN);
        /*
        Drawable d = button.getBackground();
        PorterDuffColorFilter filter = new PorterDuffColorFilter(Color.GREEN, PorterDuff.Mode.SRC_ATOP);
        d.setColorFilter(filter);*/
        //button = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
        //button.setBackgroundColor(Color.GRAY);
        /*
        d = button.getBackground();
        filter = new PorterDuffColorFilter(Color.GRAY, PorterDuff.Mode.SRC_ATOP);
        d.setColorFilter(filter);*/


    }
}
