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.Toast;

import com.android.common.executors.ThreadExecutor;
import com.android.common.utils.LogHelper;
import com.android.views.swiperefreshrecyclerview.EndlessRecyclerOnScrollListener;
import com.android.views.swiperefreshrecyclerview.HeaderAndFooterRecyclerViewAdapter;

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

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

import ai.pai.client.R;
import ai.pai.client.adapter.RecentPhotoStaggeredAdapter;
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;

public class TabRecentPhotoFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

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

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

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

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

}
