package com.cerveza.togglefunction.activities;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.support.wearable.view.drawer.WearableDrawerLayout;
import android.support.wearable.view.drawer.WearableNavigationDrawer;
import android.util.Log;
import android.view.Gravity;

import com.cerveza.togglefunction.FragmentBattery;
import com.cerveza.togglefunction.FragmentToggles;
import com.cerveza.togglefunction.FragmentWifiInfo;
import com.cerveza.togglefunction.MessageSendServiceWear;
import com.cerveza.togglefunction.api.EMessageType;
import com.cerveza.togglefunction.SharedConstants;
import com.cerveza.togglefunction.com.cerveza.togglefunction.ui.NavigationAdapter;
import com.cerveza.togglefunction.interfaces.IOnNavigationChange;
import com.cerveza.togglefunction.serializeutil.SerializeUtils;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;
import com.cerveza.togglefunction.R;

import java.io.IOException;


public class MainActivity extends WearableActivity implements GoogleApiClient.ConnectionCallbacks, MessageApi.MessageListener, IOnNavigationChange{
    private GoogleApiClient mApiClient;

    private WearableDrawerLayout mWearableDrawerLayout;
    private WearableNavigationDrawer mWearableNavigationDrawer;

    private FragmentToggles fragmentToggles;
    private FragmentBattery fragmentBattery;
    private FragmentWifiInfo fragmentWifiInfo;

    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;


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

        //fragments
        fragmentToggles = new FragmentToggles();
        fragmentBattery = new FragmentBattery();
        fragmentWifiInfo = new FragmentWifiInfo();

        fragmentManager = getFragmentManager();

        // Main Wearable Drawer Layout that wraps all content
        mWearableDrawerLayout = (WearableDrawerLayout) findViewById(R.id.drawer_layout);
        mWearableDrawerLayout.peekDrawer(Gravity.TOP);
        mWearableDrawerLayout.peekDrawer(Gravity.BOTTOM);

        // Top Navigation Drawer
        mWearableNavigationDrawer =
                (WearableNavigationDrawer) findViewById(R.id.top_navigation_drawer);
        NavigationAdapter navigationAdapter = new NavigationAdapter(this);
        mWearableNavigationDrawer.setAdapter(navigationAdapter);


        mWearableNavigationDrawer.setCurrentItem(1,false);

        mApiClient = new GoogleApiClient.Builder(this)
                .addApi(Wearable.API)
                .addConnectionCallbacks(this)
                .build();



        /*if(this.getIntent().hasExtra("MESSAGETYPE")){
            byte[] bytes = getIntent().getByteArrayExtra("MESSAGETYPE");
            new SendToDataLayerThread(MESSAGE_PATH, bytes).start();
            finish();
        }*/
    }

    // Connect to the data layer when the Activity starts
    @Override
    protected void onStart() {
        super.onStart();
        mApiClient.connect();
    }

    // Send a message when the data layer connection is successful.
    @Override
    public void onConnected(Bundle connectionHint) {
        Wearable.MessageApi.addListener(mApiClient,this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = new Intent(this,MessageSendServiceWear.class).setAction("SEND_MESSAGE").
                putExtra("MESSAGE_PATH", EMessageType.FUNCTIONS_STATE_INITIALIZE.getPath());
        this.startService(intent);
    }

    // Disconnect from the data layer when the Activity stops
    @Override
    protected void onStop() {
        Wearable.MessageApi.removeListener(mApiClient,this);
        if (null != mApiClient && mApiClient.isConnected()) {
            mApiClient.disconnect();
        }
        super.onStop();
    }

    // Placeholders for required connection callbacks
    @Override
    public void onConnectionSuspended(int cause) { }



    @Override
    public void onMessageReceived(MessageEvent messageEvent) {
        if(messageEvent.getPath().startsWith(SharedConstants.MESSAGE_PATH_TOGGLES)){
            fragmentToggles.handleMessage(messageEvent);
        }else if(messageEvent.getPath().equals(EMessageType.GET_WIFI_INFO.getPath())){
            fragmentWifiInfo.handleMessage(messageEvent);
        }else if(messageEvent.getPath().equalsIgnoreCase(EMessageType.OVERVIEW_UPDATE_BATTERY.getPath())){
            fragmentBattery.handleMessage(messageEvent);
        }

    }

    public 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;
    }

    public 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;
    }


    @Override
    public void onNavigationChange(int pos) {
        fragmentTransaction = fragmentManager.beginTransaction();
        Fragment fragment = fragmentToggles;

        switch (pos){
            case 0:
                fragment = fragmentBattery;
                break;
            case 1:
                fragment = fragmentToggles;
                break; //toggles
            case 2:
                fragment = fragmentWifiInfo;
                break; //wifi info
            case 3:
                mWearableNavigationDrawer.setCurrentItem(2,false);
                Intent intent = new Intent(this,MapsActivity.class);
                startActivity(intent);
                return;
        }

        fragmentTransaction.replace(R.id.fragment_container,fragment);
        fragmentTransaction.commit();
    }


    public class SendToDataLayerThread extends Thread {
        String path;
        byte[] data;

        SendToDataLayerThread(String path, String data) {
            this.path = path;
            this.data = data.getBytes();
        }

        SendToDataLayerThread(String path, byte[] data) {
            this.path = path;
            this.data = data;
        }

        public void run() {
            NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(mApiClient).await();
            for (Node node : nodes.getNodes()) {
                MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(mApiClient, node.getId(), path, data).await();
                if (result.getStatus().isSuccess()) {
                    Log.v(this.getClass().getName(), "new message, path: {" + path + "} sent to: " + node.getDisplayName());
                } else {
                    // Log an error
                    Log.v(this.getClass().getName(), "ERROR: failed to send Message");
                }
            }
        }

    }
}
