package ai.pai.client.fragments;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
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.text.TextUtils;
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.common.utils.TimeUtils;
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.android.views.swiperefreshrecyclerview.RecyclerViewUtils;
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.R;
import ai.pai.client.activity.MainActivity;
import ai.pai.client.adapter.RecentPhotoStaggeredAdapter;
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.services.MyLocationService;
import ai.pai.client.utils.HttpPostTask;
import ai.pai.client.utils.PhotoLoader;
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 View headerView;
    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 String[] images = new String[2];
    private TourInfoListener toutInfoListener;

    @Override
    public void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        photoList = new ArrayList<>();
        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<>();
        }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);
        RecyclerViewUtils.setFooterView(recyclerView,loadMoreView);
        headerView = LayoutInflater .from(getActivity()).inflate(R.layout.recyclerview_header_view, recyclerView, false);
        swipeRefreshLayout.setOnRefreshListener(this);
        scrollListener = new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadMore() {
                LogHelper.d(TAG,"onLoadMore");
                if(left > 0){
                    loadMoreView.setVisibility(View.VISIBLE);
                    doFetchPhotoTask();
                    fetchTourInfo();
                }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(fetchTourInfoTask!=null && fetchTourInfoTask.getStatus()== AsyncTask.Status.RUNNING){
            return;
        }
        LogHelper.d(TAG,"导游定位 每次进入首页均去请求旅行及集合信息");
        HashMap<String,String> params = new HashMap<>();
        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 data = json.getJSONObject("data");
                        String groupId = data.getString("group_id");
                        if(!TextUtils.isEmpty(groupId)){
                            Preferences.getInstance(context).setTourMode(true);
                            JSONObject group = data.getJSONObject("group");
                            JSONObject banners = group.getJSONObject("banners");
                            images[0] = banners.getString("attentions");
                            images[1] = banners.getString("schedules");
                            String phone = group.getString("phone");
                            Preferences.getInstance(context).setTourGuidePhone(phone);
                             String gatherTimeStr = group.getString("gather_at");
                            Preferences.getInstance(context).setGatherTime(TimeUtils.getStandardTimeInMiliSec(gatherTimeStr)+30*60*1000);
                            if(group.has("gather_location")){
                                String location = group.getString("gather_location");
                                Preferences.getInstance(context).setTourGatherLocation(location);
                            }
                            if(group.has("ended_at")){
                                String endTimeStr = group.getString("ended_at");
                                Preferences.getInstance(context).setTourEndTime(TimeUtils.getStandardTimeInMiliSec(endTimeStr));
                            }
                            if(group.has("gather_screenshot")){
                                String gatherMap = group.getString("gather_screenshot");
                                Preferences.getInstance(context).setGatherMap(gatherMap);
                            }
                            if(group.has("gather_lat")){
                                String lat = group.getString("gather_lat");
                                Preferences.getInstance(context).setTourGatherLat(lat);
                            }
                            if(group.has("gather_lon")){
                                String lon = group.getString("gather_lon");
                                Preferences.getInstance(context).setTourGatherLon(lon);
                            }
                        }
                    }else{
                        Preferences.getInstance(context).setTourMode(false);
                        Preferences.getInstance(context).setTourGuidePhone("");
                        Preferences.getInstance(context).setGatherTime(0);
                        Preferences.getInstance(context).setTourEndTime(0);
                        Preferences.getInstance(context).setTourGatherLocation("");
                        Preferences.getInstance(context).setGatherMap("");
                    }
                    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);
                initBanner();
                if(toutInfoListener!=null){
                    toutInfoListener.onTourInfoFetched();
                }
                if(Preferences.getInstance(context).isTourMode()){
                    LogHelper.d(TAG,"导游定位 当前是旅行模式");
                    Intent intent = new Intent(context, MyLocationService.class);
                    intent.putExtra("command",MyLocationService.COMMAND_START_LOCATION);
                    context.startService(intent);
                    checkLocationPermission();
                }else{
                    LogHelper.d(TAG,"导游定位 当前不是旅行模式");
                    Intent intent = new Intent(context, MyLocationService.class);
                    intent.putExtra("command",MyLocationService.COMMAND_DESTROY_LOCATION);
                    context.startService(intent);
                }
            }
        };
        fetchTourInfoTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.TOUR_INFO_URL);

    }

    private void checkLocationPermission(){
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                ||!Preferences.getInstance(getActivity()).isPermissionGranted()) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    2001);
        }
    }

    private void initBanner(){
        if(TextUtils.isEmpty(images[0]) && TextUtils.isEmpty(images[1])){
            RecyclerViewUtils.removeHeaderView(recyclerView);
            return;
        }
        String[] imageCopy = new String[2];
        imageCopy[0] = images[0];
        imageCopy[1] = images[1];
        if(TextUtils.isEmpty(images[0])||TextUtils.isEmpty(images[1])){
            imageCopy = new String[1];
            if(!TextUtils.isEmpty(images[0])){
                imageCopy[0] = images[0];
            }
            if(!TextUtils.isEmpty(images[1])){
                imageCopy[0] =images[1];
            }
        }
        RecyclerViewUtils.setHeaderView(recyclerView,headerView);
        banner = (ConvenientBanner)headerView.findViewById(R.id.banner_tour);
        banner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        },Arrays.asList(imageCopy)).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);
            }

            @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<>();
                            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;
                }
                if(isAdded() && refreshAdapter!=null && refreshAdapter.getPhotoList()!=null && refreshAdapter.getPhotoList().size()==0){
                    if(getActivity() instanceof  MainActivity){
                        MainActivity mainActivity = (MainActivity)getActivity();
                        mainActivity.showGuideAnim();
                    }
                }

            }
        };
        fetchPhotosTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.HOME_PHOTO_URL);
    }

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

    @Override
    public void onItemClick(int position) {
        new FullScreenImgPopup(getActivity(),images[position]).showPopupWindow();
    }

    public class NetworkImageHolderView implements Holder<String> {
        private ImageView imageView;
        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context,int position, String data) {
            ImageLoader.getInstance().displayImage(data,imageView,PhotoLoader.getPhotoOptions());
        }
    }

    public void setTourInfoListener(TourInfoListener listener){
        this.toutInfoListener = listener;
    }

    public interface TourInfoListener{
        void onTourInfoFetched();
    }

}
