package lac.contextnet.sddl_longrunningtest.service;

import java.io.IOException;
import java.io.Serializable;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;

import lac.cnclib.net.NodeConnection;
import lac.cnclib.net.NodeConnectionListener;
import lac.cnclib.sddl.message.ApplicationMessage;
import lac.cnclib.sddl.message.Message;
import lac.cnclib.sddl.serialization.Serialization;
import lac.contextnet.sddl_longrunningtest.AppConfig;
import lac.contextnet.sddl_longrunningtest.R;

import android.app.NotificationManager;
import android.content.Context;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.infopae.model.SDDLLocation;

public class ConnectionListener implements NodeConnectionListener {
	
	private Context c;
	public static ArrayList<SDDLLocation> receiveList;
	
	public ConnectionListener (Context c) {
		this.c = c;
	}

	@Override
	public void connected(NodeConnection nc) {
		ApplicationMessage am = new ApplicationMessage();
		am.setContentObject("ack");
		am.setTagList(new ArrayList<String>());
		am.setSenderID(AppConfig.getUuid(c));
		try {
			nc.sendMessage(am);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Log.d("SDDL", "Connected and Identified...");
	}

	@Override
	public void disconnected(NodeConnection nc) {
		Log.d("SDDL", "Disconnected...");
	}

	@Override
	public void internalException(NodeConnection nc, Exception e) {
		Log.d("SDDL", "InternalException...");
	}

	@Override
	public void newMessageReceived(NodeConnection nc, Message m) {
		if(m.getContentObject() instanceof ArrayList) {
			receiveList = (ArrayList) m.getContentObject();
		}
		else if(m.getContentObject() instanceof String){
			NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(c);
			mBuilder.setSmallIcon(R.drawable.ic_phone);
			mBuilder.setContentTitle("SDDL - MAPS!");
			mBuilder.setContentText("Você recebeu uma notificação de: " + m.getContentObject());

			NotificationManager mNotificationManager = (NotificationManager) c.getSystemService(Context.NOTIFICATION_SERVICE);
			mNotificationManager.notify(1, mBuilder.build());
		}

		Log.d("SDDL", "NewMessageReceived... ");
	}

	@Override
	public void reconnected(NodeConnection nc, SocketAddress s,
			boolean arg2, boolean arg3) {
		Log.d("SDDL", "Reconnected...");
	}

	@Override
	public void unsentMessages(NodeConnection nc, List<Message> lstMsg) {
		Log.d("SDDL", "UnsetMessages...");
	}

}
