package in.voiceme.app.voiceme.GroupsPages;


import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;

import in.voiceme.app.voiceme.R;
import in.voiceme.app.voiceme.infrastructure.BaseFragment;
import in.voiceme.app.voiceme.infrastructure.BaseSubscriber;
import in.voiceme.app.voiceme.infrastructure.MySharedPreferences;
import in.voiceme.app.voiceme.services.RetryWithDelay;
import link.fls.swipestack.SwipeStack;
import rx.android.schedulers.AndroidSchedulers;

import static com.facebook.GraphRequest.TAG;

/**
 * A simple {@link Fragment} subclass.
 */
public class CommunityGroupFragment extends BaseFragment implements SwipeStack.SwipeStackListener, View.OnClickListener {

    private Button mButtonLeft, mButtonRight;
    private int currentPage = PAGE_START;
    private static final int PAGE_START = 1;
    private View view;
    private ArrayList<String> groupId;
    private ProgressBar progressBar;
    private List<CommunityGroupPojo> response;
    private View progressFrame;
    private ArrayList<CommunityGroupPojo> mData;
    private SwipeStack mSwipeStack;
    private SwipeStackAdapter mAdapter;
    private LinearLayout errorLayout;
    private TextView txtError;
    private Button error_btn_retry;
    private List<CommunityGroupPojo> dataSet;
    private List<String> joinedGroupsList;


    public CommunityGroupFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_community_group, container, false);
        mSwipeStack = (SwipeStack) view.findViewById(R.id.swipeStack);
        mButtonLeft = (Button) view.findViewById(R.id.buttonSwipeLeft);
        mButtonRight = (Button) view.findViewById(R.id.buttonSwipeRight);

        joinedGroupsList = new ArrayList<>();
        progressBar = (ProgressBar) view.findViewById(R.id.main_progress);
        progressFrame = view.findViewById(R.id.community_Fragment_frame);
        txtError = (TextView) view.findViewById(R.id.error_txt_cause);
        error_btn_retry = (Button) view.findViewById(R.id.error_btn_retry);

        errorLayout = (LinearLayout) view.findViewById(R.id.error_layout);

        mButtonLeft.setOnClickListener(this);
        mButtonRight.setOnClickListener(this);

        groupId = new ArrayList<>();

        try {
            loadFirstPage();
        } catch (Exception e) {
            e.printStackTrace();
        }

       // fillWithTestData();
        return view;

    }

    private void showErrorView(Throwable throwable) {
        if (errorLayout.getVisibility() == View.GONE) {
            errorLayout.setVisibility(View.VISIBLE);
            progressBar.setVisibility(View.GONE);
            txtError.setText(fetchErrorMessage(throwable));
        }
    }

    private void loadFirstPage() throws Exception {
        Log.d(TAG, "loadFirstPage: ");
        hideErrorView();

        if(currentPage > PAGE_START){
            currentPage = PAGE_START;
        }
        application.getWebService()
                .getUserJoinedGroups("joined", MySharedPreferences.getUserId(preferences), currentPage)
                .retryWhen(new RetryWithDelay(3,2000))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<List<CommunityGroupPojo>>() {
                    @Override
                    public void onNext(List<CommunityGroupPojo> response) {

                        progressBar.setVisibility(View.GONE);
                        progressFrame.setVisibility(View.GONE);
                        hideErrorView();
                        Log.e("RESPONSE:::", "Size===" + response.size());
                        //         List<PostsModel> body = (List<PostsModel>) response.get(0).body();

                        //   List<PostsModel> model = fetchResults(response);
                        //   showRecycleWithDataFilled(response);
                        mAdapter = new SwipeStackAdapter(response);
                        mSwipeStack.setAdapter(mAdapter);
                        mSwipeStack.setListener(CommunityGroupFragment.this);

                       // mAdapter.addAll(response);
                        arraylistCurrent(response);

                    }
                    @Override
                    public void onError(Throwable e){
                        e.printStackTrace();
                        progressBar.setVisibility(View.GONE);
                        progressFrame.setVisibility(View.GONE);
                        showErrorView(e);
                    }
                });
    }

    private void arraylistCurrent(List<CommunityGroupPojo> response){
        this.response = response;
    }

    private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null;
    }

    private String fetchErrorMessage(Throwable throwable) {
        String errorMsg = getResources().getString(R.string.error_msg_unknown);

        if (!isNetworkConnected()) {
            errorMsg = getResources().getString(R.string.error_msg_no_internet);
        } else if (throwable instanceof TimeoutException) {
            errorMsg = getResources().getString(R.string.error_msg_timeout);
        }

        return errorMsg;
    }

    private void hideErrorView() {
        if (errorLayout.getVisibility() == View.VISIBLE) {
            errorLayout.setVisibility(View.GONE);
            progressBar.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean processLoggedState(View viewPrm) {
        return false;
    }


    /*
    private void fillWithTestData() {
        for (int x = 0; x < 5; x++) {
            mData.add(new CommunityGroupPojo("1", "Group Name", "1", "Category name",
                    new CreatedBy("1", "username"), false, "timeCreated", "joinedAt"));
        }
    }
    */

    @Override
    public void onClick(View v) {
        if (v.equals(mButtonLeft)) {
            mSwipeStack.swipeTopViewToLeft();
        } else if (v.equals(mButtonRight)) {
            mSwipeStack.swipeTopViewToRight();
        }
    }

    @Override
    public void onViewSwipedToLeft(int position) {
     //   String swipedElement = mAdapter.getmData().get(position).getGroupId();

    }

    @Override
    public void onViewSwipedToRight(int position) {
        if (mAdapter.getmData().get(position) != null){
            joinedGroupsList.add(mAdapter.getmData().get(position).getGroupId());
        }

    }

    @Override
    public void onPause() {


        super.onPause();
    }

    @Override
    public void onStackEmpty() {
        Toast.makeText(getActivity(), "Empty Stack", Toast.LENGTH_SHORT).show();
    }

    public class SwipeStackAdapter extends BaseAdapter {

        private List<CommunityGroupPojo> mData;

        public SwipeStackAdapter(List<CommunityGroupPojo> data) {
            this.mData = data;
            dataSet = new ArrayList<>();
        }


        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public String getItem(int position) {
            return  mData.get(position).getCategoryName();
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void addAll(List<CommunityGroupPojo> moveResults) {
            for (CommunityGroupPojo result : moveResults) {
                add(result);
            }
        }

        public List<CommunityGroupPojo> getmData() {
            return mData;
        }

        public void add(CommunityGroupPojo r) {
            dataSet.add(r);
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.swipe_card, parent, false);
            }

            SimpleDraweeView imageView = (SimpleDraweeView) convertView.findViewById(R.id.community_group_image);
            TextView textViewCard = (TextView) convertView.findViewById(R.id.textViewCard);
            TextView members_in_group = (TextView) convertView.findViewById(R.id.members_in_group);
            TextView group_tags_01 = (TextView) convertView.findViewById(R.id.group_tags_01);
            TextView group_tags_02 = (TextView) convertView.findViewById(R.id.group_tags_02);
            TextView group_tags_03 = (TextView) convertView.findViewById(R.id.group_tags_03);
            TextView group_details = (TextView) convertView.findViewById(R.id.group_details);

            group_tags_01.setText(mData.get(position).getCategoryName());
            group_details.setText(mData.get(position).getGroup_description());
            textViewCard.setText(mData.get(position).getGroupName());
            members_in_group.setText(String.valueOf(mData.get(position).getGroup_members_joined() + " " + "members" + " " +
                    mData.get(position).getGroup_posts_inside() + " " + "posts"));
            imageView.setImageURI(mData.get(position).getGroup_image_url());
            imageView.setBackground(getResources().getDrawable(R.drawable.gradient_bg));

            return convertView;
        }
    }
}