package ai.pai.client.fragments;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
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.LinearLayout;
import android.widget.Toast;

import com.android.common.utils.LogHelper;

import java.util.ArrayList;

import ai.pai.client.R;
import ai.pai.client.activity.GroupActivity;
import ai.pai.client.adapter.PhotoStaggeredAdapter;
import ai.pai.client.beans.GroupPhotoItem;
import ai.pai.client.db.DBService;
import ai.pai.client.services.GroupService;

public class GroupPhotoFragment extends BaseFragment implements  GroupService.GroupServiceListener{

    private PhotoStaggeredAdapter adapter;
    private LinearLayout noPhotoLayout;
    private ArrayList<GroupPhotoItem> photoList;
    private GroupServiceConnection serviceConnection;
    private boolean isBound;
    private String groupId;
    private Handler handler;

    @Override
    public void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        groupId = getArguments().getString("groupId");
    }

    
    @Override
    public View onCreateView(LayoutInflater inflater,  ViewGroup container,  Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_group_photo,container,false);
        RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.rv_group_photos);
        noPhotoLayout = (LinearLayout)rootView.findViewById(R.id.layout_no_photo);
        photoList = DBService.getInstance(getActivity()).getGroupPhotoListByGroupId(groupId);
        adapter = new PhotoStaggeredAdapter(getActivity(),photoList);
        recyclerView.setAdapter(adapter);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
        noPhotoLayout.setVisibility(photoList.size()==0 ? View.VISIBLE : View.INVISIBLE);
        serviceConnection = new GroupServiceConnection(this);
        handler = new Handler();
        if(!isBound){
            Intent intent = new Intent(getActivity(), GroupService.class);
            getActivity().bindService(intent,serviceConnection, Context.BIND_AUTO_CREATE);
            isBound = true;
        }
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        LogHelper.d(TAG,"photoFragment onResume and fetch photo ");
        sendFetchPhotoCommand();
    }

    @Override
    public void onPause() {
        super.onPause();
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            LogHelper.d(TAG,"photoFragment onHiddenChanged and fetch photo ");
            sendFetchPhotoCommand();
        }else{
            handler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void onDestroyView() {
        if(isBound){
            getActivity().unbindService(serviceConnection);
            serviceConnection=null;
            isBound = false;
        }
        if(handler!=null){
            handler.removeCallbacksAndMessages(null);
            handler=null;
        }
        super.onDestroyView();
    }


    private void sendFetchPhotoCommand(){
        handler.removeCallbacksAndMessages(null);
        Intent intent = new Intent(getActivity(), GroupService.class);
        Bundle bundle = new Bundle();
        bundle.putInt("command", GroupService.GroupCommand.COMMAND_FETCH_PHOTOS);
        bundle.putString("group_id",groupId);
        bundle.putString("current_id",String.valueOf(DBService.getInstance(getActivity()).getCurrentIdByGroupId(groupId)));
        intent.putExtras(bundle);
        getActivity().startService(intent);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                sendFetchPhotoCommand();
            }
        },5000);
    }

    @Override
    public void onCommandCommitFail(int command, String msg) {
        LogHelper.d(TAG,"photoFragment onCommandCommitFail ,command is  "+command);
    }

    @Override
    public void onCommandCommitSuccess(int command, Object response) {
        if(!isAdded()){
            return;
        }
        LogHelper.d(TAG,"photoFragment onCommandCommitSuccess ,command is  "+command);
        switch (command){
            case  GroupService.GroupCommand.COMMAND_UPLOAD_PHOTO:
                Toast.makeText(getActivity(),R.string.photo_upload_success,Toast.LENGTH_SHORT).show();
            case GroupService.GroupCommand.COMMAND_FETCH_PHOTOS:
                ArrayList<GroupPhotoItem> photoItems = (ArrayList<GroupPhotoItem>)response;
                if(adapter!=null&& photoItems!=null &&photoItems.size()>0){
                    if(!photoItems.get(0).groupId.equals(groupId)){
                        return;
                    }
                    LogHelper.d(TAG, "photoFragment  onCommandCommitSuccess has new photos and update adapter :"+photoItems.size());
                    noPhotoLayout.setVisibility(View.GONE);
                    adapter.addGroupPhotoItems(photoItems);
                }
                noPhotoLayout.setVisibility(adapter.getPhotoList().size()==0 ? View.VISIBLE : View.GONE);
                if(isAdded() && adapter.getPhotoList().size()==0){
                    if(getActivity() instanceof GroupActivity){
                        GroupActivity groupActivity = (GroupActivity)getActivity();
                        groupActivity.showGuideAnim();
                    }
                }
                break;
            case GroupService.GroupCommand.COMMAND_REFRESH_PHOTOS:
                ArrayList<GroupPhotoItem> photos = (ArrayList<GroupPhotoItem>)response;
                if(adapter!=null&& photos!=null){
                    adapter.refreshGroupPhotoItems(photos);
                }
                break;
        }
    }


    private static class GroupServiceConnection implements ServiceConnection {

        private GroupService.GroupServiceListener listener;

        public GroupServiceConnection(GroupService.GroupServiceListener listener){
            this.listener = listener;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            GroupService.MyBinder binder = (GroupService.MyBinder)service;
            binder.getService().registerServiceListener(listener);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

}
