package tech.starwin.service;


import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import org.greenrobot.eventbus.EventBus;

import tech.starwin.LibConfig;
import tech.starwin.R;


/**
 * Created by SiKang on 2018/9/27.
 */
public class MsgHandleService extends FirebaseMessagingService {
    public static final String TAG = "MsgHandleService";
    public static final String RECEIVED_FIREBASE_MESSAGE = "action.receivedFireBaseMessage";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        handleMsg(this, remoteMessage);

        if (remoteMessage.getNotification() != null) {
            RemoteMessage.Notification notificationInfo = remoteMessage.getNotification();
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            Notification notification = new NotificationCompat.Builder(this, "default")
                    .setContentTitle(notificationInfo.getTitle())
                    .setContentText(notificationInfo.getBody())
                    .setSmallIcon(LibConfig.APP_ICON)
                    .setWhen(System.currentTimeMillis())
                    .setTicker(notificationInfo.getTitle())
                    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                    .setAutoCancel(true)
                    .build();
            manager.notify(1, notification);
        }
    }

    @Override
    public void onDeletedMessages() {
    }

    /**
     * 处理推送内容
     */
    public static void handleMsg(Context context, RemoteMessage remoteMessage) {
        if (remoteMessage != null) {
            //EventBus 通知
            EventBus.getDefault().post(remoteMessage);
            //广播 通知
            Intent intent = remoteMessage.toIntent();
            intent.setAction(RECEIVED_FIREBASE_MESSAGE);
            context.sendBroadcast(intent);
        }

    }

}
