package com.zhaohaoting.framework.utils.notification;

import android.annotation.TargetApi;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import android.util.Log;

import static android.support.v4.app.NotificationCompat.VISIBILITY_SECRET;

/**
 * 适配Android O版本的通知栏
 * 采用
 * <p>
 * Created by huangjun on 2017/11/8.
 */

public class AVChatNotificationChannelCompat26 {
    private static String NIM_CHANNEL_ID = "zht_library_tip_channel_001";
    private static final String NIM_CHANNEL_NAME = "zht library tip channel";
    private static final String NIM_CHANNEL_DESC = "zht library tip notification";

    public static String getNIMChannelId(Context context) {
        /*
         * 适配关键：target 8.0+必须设置一个channel，8.0以下一定要返回null！否则通知栏弹不出
         */
        Log.e("NIM_CHANNEL_ID", NIM_CHANNEL_ID);
        return isBuildAndTargetO(context) ? NIM_CHANNEL_ID : null;
    }

    public static NotificationChannel createNIMMessageNotificationChannel(Context context, NotificationManager manager) {
        NotificationChannel channel = null;
        /*
         * 适配关键：只有8.0+的机器才能创建NotificationChannel，否则会找不到类。target 8.0+才需要去创建一个channel，否则就用默认通道即null
         */
        if (!isBuildAndTargetO(context)) {
            return channel;
        }
        if (manager == null) {
            manager = ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE));
        }
        if (manager != null) {
            channel = manager.getNotificationChannel(NIM_CHANNEL_ID); // 已经存在就不要再创建了，无法修改通道配置
            if (channel == null) {
                channel = buildNIMMessageChannel();
                manager.createNotificationChannel(channel);
            }
        }
        return channel;
    }


    @TargetApi(Build.VERSION_CODES.O)
    private static NotificationChannel buildNIMMessageChannel() {
        Log.e("CREATE_NIM_CHANNEL_ID", NIM_CHANNEL_ID);
        NotificationChannel channel = new NotificationChannel(NIM_CHANNEL_ID, NIM_CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW);
        channel.setDescription(NIM_CHANNEL_DESC);
        channel.enableVibration(false);
        channel.setSound(null, null);
        channel.setShowBadge(false);
        channel.setLockscreenVisibility(VISIBILITY_SECRET);//锁屏显示通知
        channel.setBypassDnd(true);
        return channel;
    }

    private static boolean isBuildAndTargetO(Context context) {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
                context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.O;
    }
}
