package jp.agentec.abook.abv.cl.push;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.util.Log;

import androidx.annotation.NonNull;

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

import java.util.Map;

import jp.agentec.abook.abv.bl.common.exception.ABVException;
import jp.agentec.abook.abv.bl.common.log.Logger;
import jp.agentec.abook.abv.bl.dto.MemberInfoDto;
import jp.agentec.abook.abv.bl.logic.AbstractLogic;
import jp.agentec.abook.abv.bl.logic.UserAuthenticateLogic;
import jp.agentec.abook.abv.cl.util.AppUtil;
import jp.agentec.abook.abv.cl.util.PreferenceUtil;
import jp.agentec.abook.abv.launcher.android.R;
import jp.agentec.abook.abv.ui.common.activity.ShowPushMessageDailogActivity;
import jp.agentec.abook.abv.ui.common.appinfo.AppDefType;
import jp.agentec.abook.abv.ui.home.activity.SplashScreenActivity;
import jp.agentec.adf.util.StringUtil;


public class ABVFcmListenerService extends FirebaseMessagingService {
    private static final String TAG = "ABVFcmListenerService";
    private NotificationManager mNotificationManager;
    private static int mNotificationConnect = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(getApplicationContext().getPackageName(), getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT);

            if (mNotificationManager != null) {
                mNotificationManager.createNotificationChannel(notificationChannel);
            }
        }
    }

    @Override
    public void onNewToken(@NonNull String token) {
        PreferenceUtil.putUserPref(this, AppDefType.UserPrefKey.NEED_SEND_TOKEN, true);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Map<String, String> msg = remoteMessage.getData();

        Log.d(TAG,"onMessageReceived(): msg :"+ msg);
        try {
            UserAuthenticateLogic logic = AbstractLogic.getLogic(UserAuthenticateLogic.class);
            MemberInfoDto memberInfo = logic.getMemberInfo();
            if (!StringUtil.isNullOrWhiteSpace(msg.get(AppDefType.PushMessageKey.message)) && this.getResources().getInteger(R.integer.push_message) == 1 && memberInfo != null) {
                if (AppUtil.isAppForground(this)) {
                    Intent pushMsgDialog = new Intent(ABVFcmListenerService.this, ShowPushMessageDailogActivity.class);
                    pushMsgDialog.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    pushMsgDialog.putExtra(AppDefType.PushMessageKey.message, msg.get(AppDefType.PushMessageKey.message));
                    pushMsgDialog.putExtra(AppDefType.PushMessageKey.data, msg.get(AppDefType.PushMessageKey.data));
                    pushMsgDialog.putExtra(AppDefType.PushMessageKey.operationId, msg.get(AppDefType.PushMessageKey.operationId));
                    startActivity(pushMsgDialog);
                } else {
                    sendNotification(msg);
                }
            }
        } catch (ABVException e) {
            // ignore
            Logger.e(TAG, e.toString());
        }
    }

    private void sendNotification(Map<String, String> message) {
        Intent intent = new Intent();

        // 定期点検用
        if (message.get(AppDefType.PushMessageKey.operationId) != null) {
            intent.putExtra(AppDefType.PushMessageKey.operationId, message.get(AppDefType.PushMessageKey.operationId));
            intent.putExtra(AppDefType.PushMessageKey.message, message.get(AppDefType.PushMessageKey.message));
        }
        intent.setClassName(getApplicationContext(), SplashScreenActivity.class.getName());

        Notification notification;

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int uniqueId = (int) System.currentTimeMillis();

            PendingIntent pendingIntent = PendingIntent.getActivity(this, uniqueId, intent, PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_IMMUTABLE);

            notification = getNotificationBuilder(pendingIntent, message).setChannelId(getApplicationContext().getPackageName()).build();

            if (mNotificationManager != null) {
                mNotificationManager.notify(uniqueId, notification);
            }
        } else {
            //mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            Notification.Builder nb = getNotificationBuilder(pendingIntent, message);

            if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
                //noinspection deprecation(API16から非推奨になった。無視)
                notification = nb.getNotification();
            } else {
                notification = nb.build();
            }

            notification.flags |= Notification.FLAG_SHOW_LIGHTS;
            notification.flags |= Notification.FLAG_AUTO_CANCEL;

            // Notification ID 증가 0~999 까지 순환
            mNotificationConnect = (mNotificationConnect + 1) % 1000;

            if (mNotificationManager != null) {
                mNotificationManager.notify(mNotificationConnect, notification);
            }
        }
    }

    private Notification.Builder getNotificationBuilder(PendingIntent pendingIntent, Map<String, String> message) {
        return new Notification.Builder(this)
                .setDefaults(Notification.DEFAULT_ALL)
                .setSmallIcon(R.drawable.icon)
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(true)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(message.get(AppDefType.PushMessageKey.message))
                .setContentIntent(pendingIntent);
    }

    private String getDownloadUrlByShareKey(String shareKey) {
        String downloadUrl = null;
        if (!StringUtil.isNullOrEmpty(shareKey)) {
            downloadUrl = "https://" + getString(R.string.repository_fqdn) + "/" + shareKey;
        }
        return downloadUrl;
    }


}
