package ai.pai.client.fragments;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.common.executors.ThreadExecutor;
import com.android.common.utils.LogHelper;
import com.android.views.banner.CBViewHolderCreator;
import com.android.views.banner.ConvenientBanner;
import com.android.views.banner.Holder;
import com.android.views.banner.OnItemClickListener;
import com.android.views.swiperefreshrecyclerview.EndlessRecyclerOnScrollListener;
import com.android.views.swiperefreshrecyclerview.HeaderAndFooterRecyclerViewAdapter;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

import ai.pai.client.BuildConfig;
import ai.pai.client.R;
import ai.pai.client.adapter.RecentPhotoStaggeredAdapter;
import ai.pai.client.beans.BannerBean;
import ai.pai.client.beans.GroupPhotoItem;
import ai.pai.client.db.DBService;
import ai.pai.client.db.Preferences;
import ai.pai.client.utils.HttpPostTask;
import ai.pai.client.utils.UrlContainer;
import ai.pai.client.views.FullScreenImgPopup;

public class TabRecentPhotoFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener,OnItemClickListener {

    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecentPhotoStaggeredAdapter refreshAdapter;
    private HeaderAndFooterRecyclerViewAdapter photoAdapter;
    private EndlessRecyclerOnScrollListener scrollListener;
    private View loadMoreView;

    private HttpPostTask fetchPhotosTask;
    private HttpPostTask fetchTourInfoTask;
    private ArrayList<GroupPhotoItem> photoList;
    private boolean isDataRefreshed;
    private int left;
    private static  final int num = 10;

    private ConvenientBanner banner;
    private ArrayList<BannerBean> bannerBeanList;

    private String[] images = {"http://img2.imgtn.bdimg.com/it/u=3093785514,1341050958&fm=21&gp=0.jpg",
            "http://img2.3lian.com/2014/f2/37/d/40.jpg",
            "http://img2.3lian.com/2014/f2/37/d/39.jpg",
            "http://www.8kmm.com/UploadFiles/2012/8/201208140920132659.jpg",
            "http://f.hiphotos.baidu.com/image/h%3D200/sign=1478eb74d5a20cf45990f9df460b4b0c/d058ccbf6c81800a5422e5fdb43533fa838b4779.jpg",
            "http://f.hiphotos.baidu.com/image/pic/item/09fa513d269759ee50f1971ab6fb43166c22dfba.jpg"
    };

    @Override
    public void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        photoList = new ArrayList<GroupPhotoItem>();
        left = Integer.MAX_VALUE;
    }

    
    @Override
    public View onCreateView(LayoutInflater inflater,  ViewGroup container,  Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_recent_photo, container, false);
        banner = (ConvenientBanner)rootView.findViewById(R.id.banner_tour);
        swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        if(Preferences.getInstance(getActivity()).isGuestLogin()){
            photoList = new ArrayList<GroupPhotoItem>();
        }else{
            photoList = DBService.getInstance(getActivity()).getRecentPhotos();
        }
        refreshAdapter = new RecentPhotoStaggeredAdapter(getActivity(), photoList);
        photoAdapter = new HeaderAndFooterRecyclerViewAdapter(refreshAdapter);
        recyclerView.setAdapter(photoAdapter);
        loadMoreView = LayoutInflater .from(getActivity()).inflate(R.layout.view_load_more, recyclerView, false);
        photoAdapter.addFooterView(loadMoreView);
        loadMoreView.setVisibility(View.GONE);
        swipeRefreshLayout.setOnRefreshListener(this);
        scrollListener = new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadMore() {
                LogHelper.d(TAG,"onLoadMore");
                if(left > 0){
                    loadMoreView.setVisibility(View.VISIBLE);
                    doFetchPhotoTask();
                }else{
                    Toast.makeText(getActivity(),R.string.no_more_content,Toast.LENGTH_SHORT).show();
                }
            }
        };
        recyclerView.addOnScrollListener(scrollListener);
        doFetchPhotoTask();
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        fetchTourInfo();
    }

    private void fetchTourInfo(){
        if(!Preferences.getInstance(getActivity()).isTourMode() && !BuildConfig.DEBUG){
            return;
        }
        if(fetchTourInfoTask!=null && fetchTourInfoTask.getStatus()== AsyncTask.Status.RUNNING){
            return;
        }
        if(BuildConfig.DEBUG){
            Preferences.getInstance(getActivity()).setTourGuidePhone("13811443340");
            bannerBeanList = new ArrayList<>();
            for(int k =0;k<6;k++){
                BannerBean bean = new BannerBean();
                bean.title = "title"+k;
                bean.url = images[k];
                bannerBeanList.add(bean);
            }
            initBanner();
            return;
        }
        HashMap<String,String> params = new HashMap<String,String>();
        String userId = Preferences.getInstance(getActivity()).getUserId();
        if(userId.length()==0){
            return;
        }
        params.put("user_id",userId);

        fetchTourInfoTask = new HttpPostTask(getActivity(),params) {


            @Override
            protected boolean parseResponse(Context context, String response) {
                try{
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if(status == 200){
                        JSONObject info = json.getJSONObject("data");

                        return true;
                    }
                }catch (Exception e){
                    LogHelper.e(TAG,"fetchTourInfo error happen "+e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
            }
        };
        fetchTourInfoTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.TOUR_INFO_URL);

    }

    private void initBanner(){
        banner.setVisibility(View.VISIBLE);
        banner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        },Arrays.asList(images)).setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused}).setOnItemClickListener(this);
        banner.startTurning(3000);
    }

    private synchronized void doFetchPhotoTask(){
        if(!isAdded()){
            return;
        }
        if(refreshAdapter==null){
            return;
        }
        if(fetchPhotosTask!=null && fetchPhotosTask.getStatus()== AsyncTask.Status.RUNNING){
            return;
        }
        final int page = isDataRefreshed  ? refreshAdapter.getPhotoList().size() /num +1 : 1;
        LogHelper.d(TAG,"doFetchPhotoTask  start with page "+page);
        HashMap<String,String> params = new HashMap<String,String>();
        String userId = Preferences.getInstance(getActivity()).getUserId();
        if(userId.length()==0){
            return;
        }
        params.put("user_id",userId);
        params.put("page",String.valueOf(page));
        params.put("num",String.valueOf(num));

        fetchPhotosTask = new HttpPostTask(getActivity(),params) {
            ArrayList<GroupPhotoItem>  photoItems;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                scrollListener.setLoading(true);
//                swipeRefreshLayout.setRefreshing(true);
            }

            @Override
            protected boolean parseResponse(Context context, String response) {
                try{
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if(status == 200){
                        LogHelper.d(TAG,"doFetchPhotoTask  parseResponse status 200");
                        JSONObject info = json.getJSONObject("data");
                        JSONArray photoArray = info.getJSONArray("photos");
                        if(photoArray!=null && photoArray.length()>0){
                            photoItems = new ArrayList<GroupPhotoItem>();
                            int len = photoArray.length();
                            for(int k = 0; k<len;k++){
                                JSONObject photoObj = photoArray.getJSONObject(k);
                                photoItems.add(GroupPhotoItem.parseFromJSON(photoObj));
                            }
                            LogHelper.d(TAG,"doFetchPhotoTask  get new photos ,count="+photoItems.size());
                        }
                        left = info.getInt("left");
                        LogHelper.d(TAG,"doFetchPhotoTask  left="+left);
                        return true;
                    }
                }catch (Exception e){
                    LogHelper.e(TAG,"doFetchPhotoTask error happen "+e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
                loadMoreView.setVisibility(View.GONE);
                swipeRefreshLayout.setRefreshing(false);
                scrollListener.setLoading(false);
                if(page == 1 && isAdded()){
                    photoItems = DBService.getInstance(context).getRecentPhotos();
                    refreshAdapter.addPhotoList(photoItems);
                }
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                loadMoreView.setVisibility(View.GONE);
                swipeRefreshLayout.setRefreshing(false);
                scrollListener.setLoading(false);
                if(photoItems!=null && photoItems.size()>0 && isAdded()){
                    LogHelper.d(TAG, " onCommandCommitSuccess has new photos and update adapter :"+photoItems.size());
                    refreshAdapter.addPhotoList(photoItems);
                    if(page==1){
                        DBService.getInstance(context).clearRecentPhotos();
                    }
                    DBService.getInstance(context).addRecentPhotos(photoItems);
                    isDataRefreshed = true;
                }
            }
        };
        fetchPhotosTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.HOME_PHOTO_URL);
    }

    @Override
    public void onRefresh() {
        LogHelper.d(TAG,"onRefresh");
        if(refreshAdapter!=null){
            refreshAdapter.clearPhotoList();
        }
        doFetchPhotoTask();
    }

    @Override
    public void onItemClick(int position) {
        new FullScreenImgPopup(getActivity(),bannerBeanList.get(position).url).showPopupWindow();
    }

    public class NetworkImageHolderView implements Holder<String> {
        private ImageView imageView;
        @Override
        public View createView(Context context) {
            //你可以通过layout文件来创建，也可以像我一样用代码创建，不一定是Image，任何控件都可以进行翻页
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context,int position, String data) {
            imageView.setImageResource(R.drawable.default_img);
            ImageLoader.getInstance().displayImage(data,imageView);
        }
    }

}
