package com.hikapro.backpack.presenter;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
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.TextUtils;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.webkit.URLUtil;
import android.widget.ImageView;
import android.widget.TextView;

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.presenter.adapters.ItemDetailAdapter;
import com.hikapro.backpack.presenter.adapters.helper.OnSwipeTouchListener;
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;

/**
 * Created by tariel on 23/04/16.
 */
public class ItemDetailPresenter implements Presenter.ItemDetail {

    private WeakReference<View.ItemDetail>  view;
    private Model.Detail                    model;
    private Model.Item                      exModel;
    private ItemDetailAdapter               adapter;
    private Item                            item;
    private int                             setId;
    private ImageView                       itemPhoto;
    private TextView                        itemDescription;
    private TextView                        itemLink;
    private int                             position;
    private ViewGroup                       progress;
    private OnSwipeTouchListener            swipeTouchListener;

    public ItemDetailPresenter(Model.Item itemModel, int startPosition) {
        this.adapter = new ItemDetailAdapter(this);
        this.exModel = itemModel;
        this.position = startPosition;
    }

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

        android.view.View view = inflater.inflate(R.layout.fragment_item_detail, container, false);

        itemPhoto = (ImageView) view.findViewById(R.id.item_photo);
        itemDescription = (TextView) view.findViewById(R.id.item_description);
        itemLink = (TextView) view.findViewById(R.id.item_link);
        progress = (ViewGroup) view.findViewById(R.id.detail_progress_container);
        progress.setVisibility(android.view.View.VISIBLE);
        swipeTouchListener = new OnSwipeTouchListener(getActivityContext()) {
            @Override
            public void onSwipeLeft() {
                swipeLeft();
            }

            @Override
            public void onSwipeRight() {
                swipeRight();
            }
        };
        progress.setOnTouchListener(swipeTouchListener);
        itemDescription.setOnTouchListener(swipeTouchListener);

        LinearLayoutManager llm = new LinearLayoutManager(getActivityContext());
        RecyclerView detailRecycler = (RecyclerView) view.findViewById(R.id.item_detail_recycler);
        detailRecycler.setLayoutManager(llm);
        detailRecycler.setAdapter(adapter);
        detailRecycler.setItemAnimator(new DefaultItemAnimator());
        //detailRecycler.addItemDecoration(new DividerDecoration(getActivityContext()));
        detailRecycler.addItemDecoration(new DividerDecoration2(getActivityContext(), R.drawable.divider, Util.dp2px(getAppContext(), 16)));

        detailRecycler.setHasFixedSize(true);
        model.setCurrentItem(exModel.getItemByPosition(position));
        model.executeQuery();

        Activity activity = (Activity) getActivityContext();
        if (activity != null) {
            activity.invalidateOptionsMenu();
            ActionBar actionBar = activity.getActionBar();
            if (actionBar != null) {
                actionBar.show();
                actionBar.setTitle(R.string.what_is_it);
                actionBar.setDisplayShowHomeEnabled(false);
                actionBar.setDisplayShowTitleEnabled(true);
                actionBar.setDisplayShowCustomEnabled(false);
                actionBar.setDisplayHomeAsUpEnabled(true);
            }
        }
        return view;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {

    }

    @Override
    public void notifyDataSetChanged() {
        adapter.notifyDataSetChanged();
        item = model.getCurrentItem();

        if (!TextUtils.isEmpty(item.getDescription())) {
            itemDescription.setText(item.getDescription());
            itemDescription.setVisibility(android.view.View.VISIBLE);
        } else {
            itemDescription.setVisibility(android.view.View.GONE);
        }

        if (item.getBuyUrls() != null && !item.getBuyUrls().isEmpty()) {
            itemLink.setVisibility(android.view.View.VISIBLE);
            itemLink.setOnClickListener(new android.view.View.OnClickListener() {
                @Override
                public void onClick(android.view.View v) {
                    if (URLUtil.isValidUrl(item.getBuyUrls().get(0))) {
                        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getBuyUrls().get(0)));

                        Activity activity = (Activity) getActivityContext();
                        if (activity != null) {
                            if (browserIntent.resolveActivity(activity.getPackageManager()) != null)
                                activity.startActivity(browserIntent);
                        }
                    }
                }
            });
        } else {
            itemLink.setVisibility(android.view.View.GONE);
            itemLink.setOnClickListener(null);
        }
    }

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

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

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

    @Override
    public Item getCurrentItem() {
        return item;
    }

    @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 notifyPictureChanged() {
        progress.setVisibility(android.view.View.GONE);
        if (model.getPicture() != null) {
            itemPhoto.setImageBitmap(model.getPicture());
            itemPhoto.setVisibility(android.view.View.VISIBLE);
            itemPhoto.setOnTouchListener(swipeTouchListener);
        } else {
            itemPhoto.setImageBitmap(null);
            itemPhoto.setVisibility(android.view.View.GONE);
        }

    }

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

    public int getSetId() {
        return setId;
    }

    private boolean isValidPosition(int position) {
        boolean ret;
        ret = position > -1 && position < exModel.getItemsCount();
        return ret;
    }

    private void swipeLeft() {
        if (isValidPosition(position + 1)) {
            // start progress
            progress.setVisibility(android.view.View.VISIBLE);
            itemPhoto.setVisibility(android.view.View.GONE);
            // load data
            model.setCurrentItem(exModel.getItemByPosition(++position));
            model.executeQuery();
            itemPhoto.setImageBitmap(null);
        }
    }

    private void swipeRight() {
        if (isValidPosition(position - 1)) {
            // start progress
            progress.setVisibility(android.view.View.VISIBLE);
            itemPhoto.setVisibility(android.view.View.GONE);
            // load data
            model.setCurrentItem(exModel.getItemByPosition(--position));
            model.executeQuery();
            itemPhoto.setImageBitmap(null);
        }
    }
}
