package com.kuckovsky.richard.home;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import io.socket.client.Ack;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;

import static com.kuckovsky.richard.home.R.id.container;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link rooms.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link rooms#newInstance} factory method to
 * create an instance of this fragment.
 */
public class rooms extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER

    // TODO: Rename and change types of parameters
    private JSONArray rooms_array;

    private OnFragmentInteractionListener mListener;

    private ListView mListView;

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


    // TODO: Rename and change types and number of parameters
    public static rooms newInstance(String rooms) {
        rooms fragment = new rooms();
        Bundle args = new Bundle();
        args.putString("rooms", rooms);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            try {
                rooms_array = new JSONArray(getArguments().getString("rooms"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_rooms, container, false);

        mListView = (ListView) rootView.findViewById(R.id.rooms_list_view);

        roomsAdapter adapter = new roomsAdapter(getActivity().getApplicationContext(), rooms_array);
        mListView.setAdapter(adapter);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                JSONObject data = new JSONObject();

                try {
                    int room_id;
                    room_id = rooms_array.getJSONObject(position).getInt("id");
                    data = new JSONObject("{room_id:" + room_id + "}");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.i("room id", data.toString());
                        SocketIO.getInstance().mSocket.emit("show_room", data, new Ack() {
                            @Override
                            public void call(Object... args) {

                                JSONObject obj = (JSONObject)args[0];
                                Log.i("load", obj.toString());
                                try {
                                    JSONObject results = obj.getJSONObject("results");

                                    Intent detailIntent = new Intent(getActivity().getApplicationContext(), room.class);

                                    Fragment  fragment2 = room.newInstance(results.toString());
                                    FragmentManager fragmentManager = getFragmentManager();
                                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                                    fragmentTransaction.replace(R.id.content, fragment2);
                                    fragmentTransaction.addToBackStack(null);
                                    fragmentTransaction.commit();

                                } catch (JSONException e) {
                                    Log.e("Chyba","Nenacitalo izbu");
                                    return;
                                }

                                //String answer = (String)args[0];
                                //Log.i("odpoved", answer);

                            }
                        });

            }

        });

        return rootView;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
