package com.hikapro.backpack.presenter;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
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.Set;
import com.hikapro.backpack.presenter.adapters.helper.AppRater;
import com.hikapro.backpack.presenter.adapters.helper.Util;
import com.hikapro.backpack.presenter.adapters.ItemListAdapter;
import com.hikapro.backpack.presenter.adapters.helper.items.DividerDecoration2;
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);
    }

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

        if (set != null) {
            android.view.View con = view.findViewById(R.id.item_list_container);
            applyBackground(con, set.getId());
        }
        return view;
    }

    private void setupActionBar() {
        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);
            }
        }
    }

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

    @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);
        rememberPosition();
    }

    private void rememberPosition() {
        LinearLayoutManager llm = (LinearLayoutManager)recycler.getLayoutManager();
        int pos = llm.findFirstVisibleItemPosition();
        model.setLastVisiblePosition(pos);
        Log.i("Last position remember", String.valueOf(pos));
    }

    @Override
    public void showDetails(int position) {
        getView().showItemDetail(getCurrentSet().getId(), model, position);
        rememberPosition();
    }

    @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();
    }

    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) {

        final Dialog dialog = new Dialog(getActivityContext());

        dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_confirm);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

        Button cancel = (Button) dialog.findViewById(R.id.button_cancel);
        Button ok = (Button) dialog.findViewById(R.id.button_ok);

        cancel.setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(android.view.View v) {
                try {
                    dialog.dismiss();
                } catch (Exception e) {

                }
            }
        });
        ok.setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(android.view.View v) {
                model.restoreSet(setId);
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    public void applyBackground(android.view.View view, int setId) {

        Drawable drawable = null;

        switch (setId) {
            case 1:
                drawable = ContextCompat.getDrawable(view.getContext(), R.drawable.ic_item_list_1);
                break;
            case 2:
                drawable = ContextCompat.getDrawable(view.getContext(), R.drawable.ic_item_list_2);
                break;
            case 3:
                drawable = ContextCompat.getDrawable(view.getContext(), R.drawable.ic_item_list_3);
                break;
            case 4:
                drawable = ContextCompat.getDrawable(view.getContext(), R.drawable.ic_item_list_4);
                break;
            case 5:
                drawable = ContextCompat.getDrawable(view.getContext(), R.drawable.ic_item_list_5);
                break;
            case 6:
                drawable = ContextCompat.getDrawable(view.getContext(), R.drawable.ic_item_list_6);
                break;
            case 7:
                // nothing
                break;
            case 8:
                drawable = ContextCompat.getDrawable(view.getContext(), R.drawable.ic_item_list_8);
                break;
            case 9:
                // nothing
                break;
            case 10:
                drawable = ContextCompat.getDrawable(view.getContext(), R.drawable.ic_item_list_10);
                break;
            case 11:
                // nothing
                break;
            case 12:
                // nothing
                break;
            case 13:
                // nothing
                break;
            case 14:
                drawable = ContextCompat.getDrawable(view.getContext(), R.drawable.ic_item_list_14);
                break;
            default:

        }
        if (drawable != null)
            view.setBackground(drawable);
        else
            view.setBackgroundColor(ContextCompat.getColor(view.getContext(), R.color.colorListBackground));

    }

    @Override
    public void onResume() {
        recycler.scrollToPosition(model.getLastVisiblePosition());
        setupActionBar();
    }

    @Override
    public void showRateDialog() {
        AppRater.showRateDialog(getActivityContext());
    }
}
