package com.b2lmobitech.spottest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MenuItem;

import com.b2lmobitech.spottest.adapter.MembersAdapter;
import com.b2lmobitech.spottest.network.MyRequestQueue;
import com.b2lmobitech.spottest.network.URL;
import com.b2lmobitech.spottest.utils.Preference;

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

import java.util.HashMap;
import java.util.Map;

public class MembersActivity extends AppCompatActivity {

    String groupId;
    RecyclerView recyclerView;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_members_activiy);

        recyclerView=findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        groupId=getIntent().getStringExtra("groupId");

        getSupportActionBar().setTitle("Members");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        getMembers();
    }

    private void getMembers() {

        Map<String, String> params = new HashMap<>();
        params.put("email", Preference.getInstance(this).getStudentId());
        params.put("groupId",groupId);

        MyRequestQueue myRequestQueue=MyRequestQueue.getInstance(this);
        myRequestQueue.addToQueue(URL.GET_MEMBERS, params, new MyRequestQueue.MyRequestFinishedListener() {
            @Override
            public void requestResult(String response) {
                try {
                    showMembers(new JSONObject(response));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void showMembers(JSONObject jsonObject) throws JSONException {
        JSONArray jsonArray=jsonObject.getJSONArray("members");
        MembersAdapter adapter=new MembersAdapter(jsonArray);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==android.R.id.home){
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }
}
