Files
BeWoPlaner/Android/BewoMitarbeiterApp/app/src/main/java/beyondsoft/bewomitarbeiterapp/ChatActivity.java
2016-09-16 14:44:58 +02:00

458 lines
18 KiB
Java

package beyondsoft.bewomitarbeiterapp;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.octo.android.robospice.SpiceManager;
import com.octo.android.robospice.UncachedSpiceService;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.request.listener.RequestListener;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapPrimitive;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import Database.DatabaseHandler;
import entities.ChatEntity;
import entities.ChatMessage;
import entities.NotificationLog;
import soapConnection.DataIdentifier;
import soapConnection.JsonSoapPrimitiveRequest;
import soapConnection.Packet;
import soapConnection.SoapCalls;
import soapConnection.SoapConnectionManager;
import tcpConnection.SocketManager;
import tcpConnection.UIHandler;
import util.ChatMessageDeserializer;
import util.ConnectivityReceiver;
import util.Util;
/**
* Created by bib on 03.05.2016.
*/
public class ChatActivity extends ActionBarActivity implements ConnectivityReceiver.ConnectivityReceiverListener {
private DatabaseHandler databaseHandler;
protected EditText text;
protected Button senden;
protected ListView listView;
public static List<ChatMessage> chatMessages;
public static ArrayAdapter<ChatMessage> adapter;
protected String recipientName;
protected int recipientPersonOid;
protected String teamMemberOids;
protected String teamMemberNames;
protected boolean isTeam;
private SpiceManager spiceManager = new SpiceManager(UncachedSpiceService.class);
private UIHandler chatUIHandler;
private View mCustomView;
private final static String LOGTAG = "CHAT_ACTIVITY";
@Override
public void onNetworkConnectionChanged(boolean isConnected) {
Util.reconnectWithServer(isConnected, ChatActivity.this);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat);
ActionBar action = getSupportActionBar();
action.setDisplayShowHomeEnabled(false);
action.setDisplayShowTitleEnabled(false);
LayoutInflater inflate = LayoutInflater.from(this);
mCustomView = inflate.inflate(R.layout.custom_menuebar, null);
action.setCustomView(mCustomView);
action.setDisplayShowCustomEnabled(true);
databaseHandler = DatabaseHandler.getInstance(this);
senden = (Button)findViewById(R.id.Sendebutton);
listView = (ListView)findViewById(R.id.list_msg);
Bundle zielkorb = getIntent().getExtras();
recipientName = zielkorb.getString("Name");
recipientPersonOid = zielkorb.getInt("RecipientOid");
byte[] bildArray = zielkorb.getByteArray("Bild");
isTeam = zielkorb.getBoolean("IsTeam");
teamMemberOids = zielkorb.getString("TeamMemberOids");
teamMemberNames = zielkorb.getString("TeamMemberNames");
ReloadChatView(recipientName, recipientPersonOid, bildArray, isTeam, teamMemberOids, teamMemberNames);
}
private void ReloadChatView(String contactName, int recipientOid, byte[] contactImage, boolean pIsTeam, String pTeamMemberOids, String pTeamMemberNames) {
chatMessages = new ArrayList<>();
recipientPersonOid = recipientOid;
recipientName = contactName;
isTeam = pIsTeam;
teamMemberOids = pTeamMemberOids;
teamMemberNames = pTeamMemberNames;
ImageView status = (ImageView) mCustomView.findViewById(R.id.status);
TextView titlename = (TextView) mCustomView.findViewById(R.id.PersonalName);
ImageView titlepic = (ImageView) mCustomView.findViewById(R.id.PersonalPic);
if(!isTeam) {
status.setImageResource((SocketManager.onlinePersonOids.contains(recipientPersonOid) ? R.drawable.statusonline : R.drawable.statusoffline));
}
Bitmap customerImage;
if(contactImage != null) {
customerImage = BitmapFactory.decodeByteArray(contactImage, 0, contactImage.length);
titlepic.setImageBitmap(GetCircleBitmap(customerImage));
}
titlename.setText(recipientName);
chatMessages = isTeam ? databaseHandler.getMessagesForTeam(recipientPersonOid) : databaseHandler.getMessagesForRecipient(recipientPersonOid);
Collections.sort(chatMessages, DATE_COMPARATOR);
adapter = new MessageAdapter(this, R.layout.item_chat_left, chatMessages);
listView.setAdapter(adapter);
chatUIHandler = new UIHandler() {
@Override
public void updateUserInterface(final Packet chatPacket) {
try {
switch(chatPacket.ChatDataIdentifier) {
case MESSAGE:
listView.post(new Runnable() {
@Override
public void run() {
if(chatPacket.SenderPersonOid == recipientPersonOid) {
chatMessages.add(new ChatMessage(chatPacket.SenderPersonOid, chatPacket.RecipientPersonOid, chatPacket.MessageTimeStamp, chatPacket.ChatMessage, true, chatPacket.ServerseitigeOid, false));
adapter.notifyDataSetChanged();
} else {
Util.SetNotify(chatPacket.ChatName, chatPacket.ChatMessage, chatPacket.SenderPersonOid, false, null, null, getApplicationContext());
}
}
});
break;
case STATUS_NOTIFICATION_LOGIN:
if(chatPacket.SenderPersonOid == recipientPersonOid) {
runOnUiThread(new Runnable() {
@Override
public void run() {
ImageView status = (ImageView) mCustomView.findViewById(R.id.status);
status.setImageResource(R.drawable.statusonline);
}
});
}
break;
case STATUS_NOTIFICATION_LOGOUT:
if(chatPacket.SenderPersonOid == recipientPersonOid) {
runOnUiThread(new Runnable() {
@Override
public void run() {
ImageView status = (ImageView) mCustomView.findViewById(R.id.status);
status.setImageResource(R.drawable.statusoffline);
}
});
}
break;
case TEAM:
listView.post(new Runnable() {
@Override
public void run() {
if(isTeam && chatPacket.RecipientPersonOid == recipientPersonOid) {
chatMessages.add(new ChatMessage(chatPacket.SenderPersonOid, chatPacket.RecipientPersonOid, chatPacket.MessageTimeStamp, chatPacket.ChatMessage, true, chatPacket.ServerseitigeOid, true));
adapter.notifyDataSetChanged();
} else {
Util.SetNotify(chatPacket.ChatName, chatPacket.ChatMessage, chatPacket.RecipientPersonOid, true, teamMemberOids, teamMemberNames, getApplicationContext());
}
}
});
break;
}
} catch(Exception pe) {
pe.printStackTrace();
}
}
};
text = (EditText)findViewById(R.id.editText);
senden.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!text.getText().toString().isEmpty()) {
Calendar c = Calendar.getInstance();
Date now = c.getTime();
Packet packet = new Packet();
packet.ChatMessage = text.getText().toString();
packet.ChatDataIdentifier = isTeam ? DataIdentifier.TEAM : DataIdentifier.MESSAGE;
if(isTeam) {
packet.ChatName = recipientName;
}
packet.RecipientPersonOid = recipientPersonOid;
packet.MessageTimeStamp = now;
packet.Tenant = SoapConnectionManager.User.getTenant();
final ChatMessage message = new ChatMessage(packet.SenderPersonOid, packet.RecipientPersonOid, packet.MessageTimeStamp, packet.ChatMessage, false, 0, isTeam);
Log.i("MESSAGE_TRACER", "ChatActivity: Speichere Nachricht in der Datenbank " + message.ChatText);
long coid = databaseHandler.addChatMessage(message);
packet.ClientseitigeOid = Long.valueOf(coid).intValue();
SocketManager.sendMessage(packet);
listView.post(new Runnable() {
@Override
public void run() {
chatMessages.add(message);
adapter.notifyDataSetChanged();
text.setText("");
}
});
} else {
Toast.makeText(ChatActivity.this, "Dieses Feld darf nicht leer sein", Toast.LENGTH_SHORT).show();
}
}
});
ArrayList<Integer> test = isTeam ? databaseHandler.getExistingTeamChatMessageIds() : databaseHandler.getExistingChatMessageIds();
Log.i(LOGTAG, "Chat-Messages in der Datenbank: " + test.size());
String pExceptions = "";
for(int i = 0; i < test.size(); i++) {
pExceptions += test.get(i);
if(i < test.size() - 1) {
pExceptions += ";";
}
}
ArrayList<PropertyInfo> propertyInfos = new ArrayList<>();
propertyInfos.add(SoapConnectionManager.BuildProperty("pSenderPersonOid", SoapConnectionManager.User.getPersonOid(), Long.class));
propertyInfos.add(SoapConnectionManager.BuildProperty("pRecipientPersonOid", recipientPersonOid, Long.class));
propertyInfos.add(SoapConnectionManager.BuildProperty("pExceptions", pExceptions, String.class));
propertyInfos.add(SoapConnectionManager.BuildProperty("pIsForTeam", isTeam, Boolean.class));
JsonSoapPrimitiveRequest request = new JsonSoapPrimitiveRequest(SoapCalls.GET_ALL_CHAT_MESSAGES, propertyInfos);
spiceManager.execute(request, new JsonSoapPrimitiveRequestListener());
NotificationManager mNotifyMgr = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
ChatEntity entity = new ChatEntity(recipientOid, isTeam);
if(SocketManager.notificationEntities.get(entity) != null) {
mNotifyMgr.cancel(SocketManager.notificationEntities.get(entity).getNotificationId());
Util.removeMessagesCount(entity);
}
}
@Override
public void onResume() {
SocketManager.uiHandler = chatUIHandler;
BeWoChatApplication.getInstance().setConnectivityListener(this);
super.onResume();
}
@Override
public void onStop(){
spiceManager.shouldStop();
super.onStop();
}
@Override
public void onPause() {
super.onPause();
}
@Override
protected void onStart() {
super.onStart();
spiceManager.start(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menue_chat, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_logout:
SocketManager.logout();
Intent intent = new Intent(ChatActivity.this, LoginActivity.class);
ChatActivity.this.startActivity(intent);
return true;
case R.id.action_doku:
Intent dokuActivity = new Intent(ChatActivity.this, WebdokuActivity.class);
ChatActivity.this.startActivity(dokuActivity);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Bundle zielkorb = intent.getExtras();
String rn = zielkorb.getString("Name");
int rpoid = zielkorb.getInt("RecipientOid");
boolean blahIsTeam = zielkorb.getBoolean("IsTeam");
String tMemberOids = zielkorb.getString("TeamMemberOids");
String tMemberNames = zielkorb.getString("TeamMemberNames");
byte[] imageAsByteArray = databaseHandler.getUserImage(rpoid);
Log.i("ON_NEW_INTENT", "Erzeuge neuen Intent");
ReloadChatView(rn, rpoid, imageAsByteArray, blahIsTeam, tMemberOids, tMemberNames);
}
private Bitmap GetCircleBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
int color = Color.RED;
Paint paint = new Paint();
Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
RectF rectF = new RectF(rect);
//bis hierhin war alles final
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawOval(rectF, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
bitmap.recycle();
return output;
}
private final class JsonSoapPrimitiveRequestListener implements RequestListener<SoapPrimitive> {
@Override
public void onRequestFailure(SpiceException spiceException) {
Log.e("GET_ALL_MESSAGES", "" + spiceException.getMessage());
}
@Override
public void onRequestSuccess(SoapPrimitive soapPrimitive) {
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(ChatMessage.class, new ChatMessageDeserializer());
Gson gson = builder.create();
Type listType = new TypeToken<ArrayList<ChatMessage>>(){}.getType();
final ArrayList<ChatMessage> result = gson.fromJson(soapPrimitive.toString(), listType);
Log.i(LOGTAG, "Chat-Messages aus der Serveranfrage: " + result.size());
String abc = "";
for(ChatMessage m : result) {
abc += "\t" + m.ChatText;
if(result.indexOf(m) < result.size() - 1) {
abc += "\n";
}
}
Log.i(LOGTAG, "Heruntergeladene Nachrichten:\n" + abc);
databaseHandler.addChatMessages(result);
listView.post(new Runnable() {
@Override
public void run() {
Collections.sort(result, DATE_COMPARATOR);
chatMessages.addAll(result);
adapter.notifyDataSetChanged();
}
});
}
}
public static final Comparator<ChatMessage> DATE_COMPARATOR = new Comparator<ChatMessage>() {
@Override
public int compare(ChatMessage lhs, ChatMessage rhs) {
return lhs.InsTs.getTime() > rhs.InsTs.getTime() ? 0 : 1;
}
};
}