package com.kuckovsky.richard.home;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
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.ListAdapter;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;

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

import java.util.ArrayList;

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


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link room.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link room#newInstance} factory method to
 * create an instance of this fragment.
 */
public class room extends Fragment {

    private JSONObject room_array;

    private OnFragmentInteractionListener mListener;

    private ListView sensorListView;
    private ListView outputListView;

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

    public static room newInstance(String room) {
        room fragment = new room();
        Bundle args = new Bundle();
        args.putString("room", room);
        fragment.setArguments(args);
        return fragment;
    }

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

    JSONArray sensors = null;
    JSONArray outputs = null;

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

        Log.i("data", room_array.toString());

        try {
            sensors = room_array.getJSONArray("sensors");
            outputs = room_array.getJSONArray("outputs");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        sensorListView = (ListView) rootView.findViewById(R.id.sensors_list_view);
        roomSensorAdapter Sadapter = new roomSensorAdapter(getActivity().getApplicationContext(), sensors);
        sensorListView.setAdapter(Sadapter);

        outputListView = (ListView) rootView.findViewById(R.id.outputs_list_view);
        roomOutputAdapter Oadapter = new roomOutputAdapter(getActivity().getApplicationContext(), outputs);
        outputListView.setAdapter(Oadapter);

        ListUtils.setDynamicHeight(sensorListView);
        ListUtils.setDynamicHeight(outputListView);

        final ArrayList<Integer> ids = new ArrayList<>();

        for(int i = 0; i < outputs.length(); i++) {
            try {
                ids.add(outputs.getJSONObject(i).getInt("id"));

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        SocketIO.getInstance().mSocket.on("output_update", new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                Log.i("update", "update");
                JSONObject obj = (JSONObject)args[0];
                try {
                    if(ids.contains(obj.getInt("id"))) {
                        if (outputs.getJSONObject(ids.indexOf(obj.getInt("id"))).getString("type").compareTo("switch") == 0) {
                            if (obj.getInt("value") == 0) {
                                updateSwitch(ids.indexOf(obj.getInt("id")), false);
                            } else {
                                updateSwitch(ids.indexOf(obj.getInt("id")), true);
                            }
                        } else if(outputs.getJSONObject(ids.indexOf(obj.getInt("id"))).getString("type").compareTo("slider") == 0) {
                            Log.i("update", "podmienka ok");
                            updateSlider(ids.indexOf(obj.getInt("id")), (obj.getInt("value") - outputs.getJSONObject(ids.indexOf(obj.getInt("id"))).getInt("min_value")));
                            Log.i("update", "ignoracia?");
                        }
                    }

                } catch (JSONException e) {
                    Log.e("Chyba","");
                    return;
                }
                //String answer = (String)args[0];
                //Log.i("odpoved", answer);
            }
        });

        return rootView;
    }

    private void updateSwitch(int index, final boolean checked){
        View v = outputListView.getChildAt(index - outputListView.getFirstVisiblePosition());

        if(v == null)
            return;

        final Switch s = (Switch) v.findViewById(R.id.switch1);
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                s.setChecked(checked);
            }
        });
    }

    private void updateSlider(int index, final int value){
        Log.i("zmena id", "watafak");
        View v = outputListView.getChildAt(index - outputListView.getFirstVisiblePosition());
        Log.i("zmena id", String.valueOf(index));
        if(v == null)
            return;
        Log.i("zmena", "ok");
        final SeekBar s = (SeekBar) v.findViewById(R.id.slider);
        s.post(new Runnable() {
            @Override
            public void run() {
                s.setProgress(0);
                s.setProgress(value);
                Log.i("zmena malo", String.valueOf(value));
                s.refreshDrawableState();
                Log.i("zmena hmm", String.valueOf(s.getProgress()));
            }
        });
    }

    public static class ListUtils {
        public static void setDynamicHeight(ListView mListView) {
            ListAdapter mListAdapter = mListView.getAdapter();
            if (mListAdapter == null) {
                // when adapter is null
                return;
            }
            int height = 0;
            int desiredWidth = View.MeasureSpec.makeMeasureSpec(mListView.getWidth(), View.MeasureSpec.UNSPECIFIED);
            for (int i = 0; i < mListAdapter.getCount(); i++) {
                View listItem = mListAdapter.getView(i, null, mListView);
                listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
                height += listItem.getMeasuredHeight();
            }
            ViewGroup.LayoutParams params = mListView.getLayoutParams();
            params.height = height + (mListView.getDividerHeight() * (mListAdapter.getCount() - 1));
            mListView.setLayoutParams(params);
            mListView.requestLayout();
        }
    }


    // 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);
    }
}
