package com.cerveza.togglefunction;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.cerveza.togglefunction.api.ControlFunction;
import com.cerveza.togglefunction.api.EMessageType;
import com.cerveza.togglefunction.com.cerveza.togglefunction.ui.Adapter;
import com.cerveza.togglefunction.serializeutil.SerializeUtils;
import com.google.android.gms.wearable.MessageEvent;

import java.io.IOException;
import java.util.List;

/**
 * Created by cerveza on 23/02/2017.
 */

public class FragmentToggles extends Fragment {

    private List<ControlFunction> listElements;
    private Adapter adapter;
    private boolean isFocused;

    public FragmentToggles() {
        listElements = SharedConstants.getFunctionControls();
        isFocused = false;
    }

    @Override
    public void onAttach(Context context) {
        /*this.context = context;
        mListener = (OnFragmentSwitchListener) getActivity();*/
        super.onAttach(context);
    }

    @Override
    public void onAttach(Activity activity) {
       /* this.context = activity.getApplicationContext();
        mListener = (OnFragmentSwitchListener) getActivity();*/
        super.onAttach(activity);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_toggles, container, false);

        // Get the list component from the layout of the activity
        RecyclerView recyclerView =
                (RecyclerView) view.findViewById(R.id.toggle_list);
        recyclerView.setNestedScrollingEnabled(true);

        // Assign an adapter to the list
        adapter = new Adapter(getActivity(), listElements);

        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));


        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        isFocused = true;
        adapter.refresh(listElements);
    }

    @Override
    public void onPause() {
        super.onPause();
        isFocused = false;
    }

    public void handleMessage(MessageEvent messageEvent){
        if(messageEvent.getPath().equals(EMessageType.FUNCTIONS_STATE_SYNCHRONIZATION.getPath())){
            synchronizeControls(messageEvent);

        }else if(messageEvent.getPath().equals(EMessageType.FUNCTIONS_STATE_INITIALIZE.getPath())){
            resetControls();
            synchronizeControls(messageEvent);
        }
    }

    private void synchronizeControls(MessageEvent messageEvent){
        List<ControlFunction> controls = (List<ControlFunction>)deserializeData(messageEvent.getData());

        int index = 0;
        for (ControlFunction ncontrol:controls) {
            for (ControlFunction control: listElements) {
                if(control.hashCode() == ncontrol.hashCode()){
                    index = listElements.indexOf(control);
                }
            }
            listElements.set(index,ncontrol);
        }

        if(isFocused){
            adapter.refresh(listElements);
        }
    }

    private Object deserializeData(byte[] bytes){
        Object object;
        try {
            object = SerializeUtils.convertFromBytes(bytes);
            return object;
        } catch (IOException e) {
            Log.e(getClass().getName(),"IO exeption during converting from byte[] to object",e);
        } catch (ClassNotFoundException e) {
            Log.e(getClass().getName(),"deserilization exception could not find class ControlFunction",e);
        }
        return null;
    }

    private byte[] serialize (Object object){
        byte[] bytes;
        try {
            bytes = SerializeUtils.convertToBytes(object);
            return bytes;
        } catch (IOException e) {
            Log.e(getClass().getName(),"IO exeption during converting from object to bytes",e);
        }
        return null;
    }

    private void resetControls(){
        for (ControlFunction control: listElements) {
            control.setDefaultState();
        }
    }
}
