package com.miraclegarden.smsmessage.service;

import android.app.Notification;
import android.os.Bundle;
import android.os.Parcelable;
import android.service.notification.StatusBarNotification;
import android.text.TextUtils;

/**
 * 通知内容多层提取工具，兼容不同厂商字段差异。
 * Telegram 常用 InboxStyle / MessagingStyle，不能只读 EXTRA_TEXT。
 */
public class NotificationExtractor {

    private static final String EXTRA_MESSAGES = "android.messages";
    private static final String EXTRA_CONVERSATION_TITLE = "android.conversationTitle";

    private NotificationExtractor() {
    }

    public static Result extract(StatusBarNotification sbn) {
        long timestamp = System.currentTimeMillis();
        if (sbn == null || sbn.getNotification() == null) {
            return new Result("", "", timestamp);
        }

        Notification notification = sbn.getNotification();
        Bundle extras = notification.extras;

        String title = "";
        String content = "";

        if (extras != null) {
            title = pickFirstNonEmpty(
                    extras.getCharSequence(Notification.EXTRA_TITLE),
                    extras.getCharSequence(Notification.EXTRA_TITLE_BIG),
                    extras.getCharSequence(EXTRA_CONVERSATION_TITLE),
                    extras.getCharSequence(Notification.EXTRA_SUMMARY_TEXT)
            );

            content = pickFirstNonEmpty(
                    extras.getCharSequence(Notification.EXTRA_TEXT),
                    extras.getCharSequence(Notification.EXTRA_BIG_TEXT),
                    extras.getCharSequence(Notification.EXTRA_INFO_TEXT),
                    extras.getCharSequence(Notification.EXTRA_SUB_TEXT),
                    extractMessagingStyleContent(extras),
                    extractInboxLines(extras)
            );
        }

        if (TextUtils.isEmpty(title)) {
            title = firstSegment(notification.tickerText);
        }

        if (TextUtils.isEmpty(content)) {
            content = normalized(notification.tickerText);
        }

        if (TextUtils.isEmpty(content) && !TextUtils.isEmpty(title)
                && normalized(notification.tickerText).startsWith(title)) {
            String ticker = normalized(notification.tickerText);
            if (ticker.length() > title.length()) {
                content = ticker.substring(title.length()).trim();
            }
        }

        return new Result(title, content, timestamp);
    }

    /** Telegram 等 App 的 InboxStyle：最新消息在 textLines 末尾。 */
    private static String extractInboxLines(Bundle extras) {
        CharSequence[] lines = extras.getCharSequenceArray(Notification.EXTRA_TEXT_LINES);
        if (lines == null || lines.length == 0) {
            return "";
        }
        for (int i = lines.length - 1; i >= 0; i--) {
            String line = normalized(lines[i]);
            if (!TextUtils.isEmpty(line)) {
                return line;
            }
        }
        return "";
    }

    /** MessagingStyle：从 android.messages 取最新一条正文。 */
    private static String extractMessagingStyleContent(Bundle extras) {
        Parcelable[] messages = extras.getParcelableArray(EXTRA_MESSAGES);
        if (messages == null || messages.length == 0) {
            return "";
        }
        for (int i = messages.length - 1; i >= 0; i--) {
            String text = extractMessagingMessageText(messages[i]);
            if (!TextUtils.isEmpty(text)) {
                return text;
            }
        }
        return "";
    }

    private static String extractMessagingMessageText(Parcelable parcelable) {
        if (parcelable == null) {
            return "";
        }
        if (parcelable instanceof Bundle) {
            Bundle bundle = (Bundle) parcelable;
            return pickFirstNonEmpty(
                    bundle.getCharSequence("text"),
                    bundle.getCharSequence(Notification.EXTRA_TEXT)
            );
        }
        return "";
    }

    private static String pickFirstNonEmpty(CharSequence... values) {
        if (values == null || values.length == 0) {
            return "";
        }
        for (CharSequence value : values) {
            String normalized = normalized(value);
            if (!TextUtils.isEmpty(normalized)) {
                return normalized;
            }
        }
        return "";
    }

    private static String normalized(CharSequence value) {
        if (value == null) {
            return "";
        }
        String result = value.toString().trim();
        if (TextUtils.isEmpty(result)) {
            return "";
        }
        if ("null".equalsIgnoreCase(result)) {
            return "";
        }
        return result;
    }

    private static String firstSegment(CharSequence tickerText) {
        String ticker = normalized(tickerText);
        if (TextUtils.isEmpty(ticker)) {
            return "";
        }
        int spaceIndex = ticker.indexOf(' ');
        if (spaceIndex > 0) {
            return ticker.substring(0, spaceIndex).trim();
        }
        return ticker;
    }

    public static class Result {
        public String title;
        public String content;
        public long timestamp;

        public Result(String title, String content, long timestamp) {
            this.title = title == null ? "" : title;
            this.content = content == null ? "" : content;
            this.timestamp = timestamp;
        }
    }
}
