package com.nutrition.express.main;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.nutrition.express.R;
import com.nutrition.express.blogposts.PostListActivity;
import com.nutrition.express.common.CommonRVAdapter;
import com.nutrition.express.common.CommonViewHolder;
import com.nutrition.express.model.data.DataManager;
import com.nutrition.express.model.helper.SearchHistoryHelper;
import com.nutrition.express.taggedposts.TaggedActivity;
import com.nutrition.express.util.FrescoUtils;

/**
 * Created by huang on 11/2/16.
 */

public class SearchFragment extends Fragment {
    private RecyclerView recyclerView;
    private SearchHistoryHelper historyHelper;
    private CommonRVAdapter adapter;
    private boolean loaded = false;
    private DataManager dataManager = DataManager.getInstance();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search, container, false);
        recyclerView = (RecyclerView) view.findViewById(R.id.blog_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        SearchView searchView = (SearchView) view.findViewById(R.id.searchView);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                openBlogPosts(query);
//                openTaggedPosts(query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isResumed()) {
            showSearchHistory();
            if (adapter.getItemCount() < dataManager.getReferenceBlog().size()) {
                adapter.notifyItemRangeInserted(adapter.getItemCount(),
                        dataManager.getReferenceBlog().size() - adapter.getItemCount());
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint()) {
            showSearchHistory();
        }
    }

    private void showSearchHistory() {
        if (loaded) {
            return;
        }
        historyHelper = new SearchHistoryHelper();

        CommonRVAdapter.Builder builder = CommonRVAdapter.newBuilder();
//        builder.setData(historyHelper.getHistories());
        builder.setData(dataManager.getReferenceBlog());
        builder.addItemType(String.class, R.layout.item_search_refer_blog,
                new CommonRVAdapter.CreateViewHolder() {
                    @Override
                    public CommonViewHolder createVH(View view) {
                        return new BaseVH(view);
                    }
                });
        adapter = builder.build();
        recyclerView.setAdapter(adapter);
        loaded = true;
    }

    private void openBlogPosts(String blogName) {
        Intent intent = new Intent(getActivity(), PostListActivity.class);
        intent.putExtra("blog_name", blogName);
        startActivity(intent);
        historyHelper.add(blogName);
        adapter.notifyDataSetChanged();
    }

    private void openTaggedPosts(String tag) {
        Intent intent = new Intent(getActivity(), TaggedActivity.class);
        intent.putExtra("tag", tag);
        startActivity(intent);
        historyHelper.add(tag);
        adapter.notifyDataSetChanged();
    }

    private void showDeleteDialog(final  String text, final int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("删除记录" + text + "?");
        builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                historyHelper.remove(text);
                adapter.notifyItemRemoved(position);
            }
        });
        builder.create().show();
    }

    public class BaseVH extends CommonViewHolder<String>
            implements View.OnClickListener, View.OnLongClickListener {
        String name;
        TextView textView;
        SimpleDraweeView avatarView;

        public BaseVH(View itemView) {
            super(itemView);
            itemView.setOnClickListener(this);
//            itemView.setOnLongClickListener(this);
            textView = (TextView) itemView.findViewById(R.id.blog_name);
            avatarView = (SimpleDraweeView) itemView.findViewById(R.id.blog_avatar);
        }

        @Override
        public void bindView(String object) {
            name = object;
            textView.setText(name);
            FrescoUtils.setTumblrAvatarUri(avatarView, name, 128);
        }

        @Override
        public void onClick(View v) {
            openBlogPosts(name);
//            openTaggedPosts(name);
        }

        @Override
        public boolean onLongClick(View v) {
            showDeleteDialog(name, getAdapterPosition());
            return true;
        }
    }


}

@@ -829,71 +829,8 @@
 er;%0A
-import com.nutrition.express.model.helper.SearchHistoryHelper;%0A
 impo
@@ -874,32 +874,32 @@
 TaggedActivity;%0A
+
 import com.nutri
@@ -1053,24 +1053,26 @@
 cyclerView;%0A
+//
     private 
@@ -1102,24 +1102,24 @@
 toryHelper;%0A
-
     private 
@@ -1243,16 +1243,47 @@
 tance();
+%0A    private int referSize = 0;
 %0A%0A    @N
@@ -2451,38 +2451,25 @@
     if (
-adapter.getItemCount()
+referSize
  %3C dataM
@@ -2552,38 +2552,25 @@
 nserted(
-adapter.getItemCount()
+referSize
 ,%0A      
@@ -2631,30 +2631,84 @@
 ) - 
-adapter.getItemCount()
+referSize);%0A                referSize = dataManager.getReferenceBlog().size(
 );%0A 
@@ -2975,32 +2975,34 @@
 turn;%0A        %7D%0A
+//
         historyH
@@ -3035,16 +3035,75 @@
 elper();
+%0A        referSize = dataManager.getReferenceBlog().size();
 %0A%0A      
@@ -3904,32 +3904,34 @@
 tivity(intent);%0A
+//
         historyH
@@ -3943,32 +3943,32 @@
 .add(blogName);%0A
-
         adapter.
@@ -4182,24 +4182,26 @@
 ty(intent);%0A
+//
         hist
@@ -4216,24 +4216,24 @@
 r.add(tag);%0A
-
         adap
@@ -4642,24 +4642,26 @@
 e, int i) %7B%0A
+//
             

fix bug: refresh reference blog