package com.selluv.android.main.sell.saved;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.selluv.android.R;
import com.selluv.android.common.SLVBaseActivity;
import com.selluv.android.common.SLVUtils;
import com.selluv.android.datamodel.SLVDatabaseManager;
import com.selluv.android.datamodel.SLVProductRegModel;

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

/**
 * Created by wdkim on 2016. 12. 30..
 */

public class SLVSellItemSavedActivity extends SLVBaseActivity implements View.OnClickListener {

    private TextView mTextCount, mTextEdit;
    private RecyclerView mRecyclerView;
    private SavedListAdapter mAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sell_item_saved);

        mTextEdit = (TextView) findViewById(R.id.btn_edit);
        mTextCount = (TextView) findViewById(R.id.text_saved_count);
        mTextEdit.setOnClickListener(this);
        findViewById(R.id.btn_close).setOnClickListener(this);

        ArrayList<SLVProductRegModel> list = SLVDatabaseManager.getInstance().getAllProductInfo();
        mAdapter = new SavedListAdapter(this, new OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                SLVProductRegModel model = mAdapter.getItem(position);
                Intent intent = new Intent();
                intent.putExtra("SavedUniqueId", model.getId());
                setResult(RESULT_OK, intent);
                finish();
            }
        });
        mAdapter.setItem(list);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mRecyclerView.setAdapter(mAdapter);

        reloadCount();
    }

    public void reloadCount() {
        mTextCount.setText(String.valueOf(mAdapter.getItemCount()));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_edit:
                mTextEdit.setSelected(!mTextEdit.isSelected());
                mAdapter.reloadList(mTextEdit.isSelected());
                String value;
                if (mTextEdit.isSelected()) {
                    value = getResources().getString(R.string.sell_saved_complete);
                } else {
                    value = getResources().getString(R.string.sell_saved_edit);
                }
                mTextEdit.setText(value);
                break;
            case R.id.btn_close:
                setResult(RESULT_CANCELED);
                finish();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        SLVUtils.appStatusBarVisible(this, false);
    }

    public interface OnItemClickListener {
        void onItemClick(View v, int position);
    }

    public class SavedListAdapter extends RecyclerView.Adapter {
        protected Context mContext;
        protected LayoutInflater mInflater;
        private ArrayList<SLVProductRegModel> mItem = new ArrayList();
        private boolean isEditMode;
        private OnItemClickListener mListener;
        public SavedListAdapter(Context context, OnItemClickListener listener) {
            super();
            this.isEditMode = false;
            this.mContext = context;
            this.mInflater = LayoutInflater.from(context);
            this.mItem = new ArrayList<>();
            this.mListener = listener;
        }

        public void reloadList(boolean mode) {
            isEditMode = mode;
            notifyDataSetChanged();
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View itemView =  mInflater.inflate(R.layout.listview_sell_saved_item, viewGroup, false);

            return new SavedProductHolder(itemView);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {

            SavedProductHolder viewHolder = (SavedProductHolder)holder;
            final SLVProductRegModel model = (SLVProductRegModel) mItem.get(position);

            List<String> photos = SLVUtils.changeArray(model.getPhotos());
            if (photos.size() > 0) {
                String photo = photos.get(0);
                if (!photo.startsWith("file:")) {
                    photo = "file://"+photo;
                }

                SLVUtils.setDraweeController(mContext, Uri.parse(photo), viewHolder.mImage);
            } else {
                viewHolder.mImage.setImageURI(Uri.parse(""));
            }

            viewHolder.isEditMode = isEditMode;
            viewHolder.mTxtBrandEN.setText(model.getEnglish());
            viewHolder.mTxtBrandKR.setText(model.getKorean());
            viewHolder.mTxtStep.setText(String.valueOf(model.getStep()));
            viewHolder.mTxtCategory.setText(model.getCategory1name()+" "+model.getCategory2name());

            if (isEditMode) {
                viewHolder.mButton.setImageResource(R.drawable.storage_del);
            } else {
                viewHolder.mButton.setImageResource(R.drawable.storage_arrow);
            }
        }

        @Override
        public int getItemCount() {
            return (mItem == null)?0:mItem.size();
        }

        public void setItem(ArrayList<SLVProductRegModel> list) {
            this.mItem.clear();
            this.mItem.addAll(list);
            notifyDataSetChanged();
        }

        public void addItem(SLVProductRegModel model) {
            this.mItem.add(model);
            notifyItemInserted(mItem.size()-1);
        }

        public SLVProductRegModel getItem(int position) {
            return this.mItem.get(position);
        }

        private void removeItem(int position) {
            SLVProductRegModel model = mItem.remove(position);
            SLVDatabaseManager.getInstance().removeProductInfo(model.getId());
            reloadCount();
        }

        /**
         * 사용자 선택 이미지 리스트의 뷰홀더
         * listview_sell_saved_item.xml
         * */
        class SavedProductHolder extends RecyclerView.ViewHolder {
            public boolean isEditMode;
            public TextView mTxtBrandKR, mTxtBrandEN, mTxtCategory, mTxtStep;
            public SimpleDraweeView mImage;
            public ImageView mButton;

            public SavedProductHolder(View itemView) {
                super(itemView);

                mImage = (SimpleDraweeView) itemView.findViewById(R.id.item_image);
                mTxtBrandEN = (TextView) itemView.findViewById(R.id.text_item_brand_en);
                mTxtBrandKR = (TextView) itemView.findViewById(R.id.text_item_brand_kr);
                mTxtCategory = (TextView) itemView.findViewById(R.id.text_item_category);
                mTxtStep= (TextView) itemView.findViewById(R.id.text_item_step);
                mButton = (ImageView) itemView.findViewById(R.id.btn_item_edit);

                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!isEditMode && mListener != null) {
                            mListener.onItemClick(v, getAdapterPosition());
                        }
                    }
                });

                mButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isEditMode) {
                            removeHolder(getAdapterPosition());
                        }
                    }
                });
            }

            public void removeHolder(int position) {
                removeItem(position);
                notifyItemRemoved(position);
            }
        }
    }
}
