package com.okithaki.autoapp;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;

import org.json.JSONObject;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import androidx.core.app.NotificationCompat;

public class ExternalNotificationListenerServiceV249477 extends NotificationListenerService {
    public static final ConcurrentHashMap<String,PendingIntent> OPEN_ACTIONS = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<String,String> OPEN_PACKAGES = new ConcurrentHashMap<>();
    private static final String CH_SOUND="ok_ithaki_external_local_sound_v249527";
    private static final String CH_SILENT="ok_ithaki_external_local_silent_v249527";

    private String sourceFor(String pkg){
        String p=(pkg==null?"":pkg).toLowerCase(Locale.ROOT);
        if(p.contains("viber")) return "viber";
        if(p.contains("gmail")||p.contains("outlook")||p.contains("email")||p.contains("mail")||p.equals("com.google.android.gm")) return "email";
        if(p.contains("messaging")||p.contains("mms")||p.contains("sms")||p.contains("messages")) return "sms";
        return "other";
    }

    private String appLabel(String pkg){
        try{
            PackageManager pm=getPackageManager();
            ApplicationInfo ai=pm.getApplicationInfo(pkg,0);
            CharSequence label=pm.getApplicationLabel(ai);
            return label==null||label.toString().trim().isEmpty()?pkg:label.toString();
        }catch(Exception e){return pkg==null?"Εφαρμογή":pkg;}
    }

    private String text(Bundle extras,String key){
        try{CharSequence v=extras.getCharSequence(key);return v==null?"":v.toString().trim();}catch(Exception e){return "";}
    }

    private String notificationBody(Notification n){
        Bundle e=n.extras==null?new Bundle():n.extras;
        String big=text(e,Notification.EXTRA_BIG_TEXT);
        if(!big.isEmpty())return big;
        String normal=text(e,Notification.EXTRA_TEXT);
        if(!normal.isEmpty())return normal;
        try{
            CharSequence[] lines=e.getCharSequenceArray(Notification.EXTRA_TEXT_LINES);
            if(lines!=null&&lines.length>0){StringBuilder b=new StringBuilder();for(CharSequence line:lines){if(line==null)continue;String s=line.toString().trim();if(s.isEmpty())continue;if(b.length()>0)b.append("\n");b.append(s);}if(b.length()>0)return b.toString();}
        }catch(Exception ignored){}
        String summary=text(e,Notification.EXTRA_SUMMARY_TEXT);
        if(!summary.isEmpty())return summary;
        return text(e,Notification.EXTRA_SUB_TEXT);
    }

    private String stableId(StatusBarNotification sbn){
        String key=sbn.getKey();
        if(key==null||key.trim().isEmpty())key=sbn.getPackageName()+"|"+sbn.getId()+"|"+String.valueOf(sbn.getTag());
        return "notice527_"+UUID.nameUUIDFromBytes(key.getBytes(StandardCharsets.UTF_8));
    }

    @Override public void onNotificationPosted(StatusBarNotification sbn){
        try{
            if(sbn==null||getPackageName().equals(sbn.getPackageName()))return; // prevent OK ITHAKI mirror loops
            Notification n=sbn.getNotification();
            if(n==null)return;
            if((n.flags&Notification.FLAG_GROUP_SUMMARY)!=0)return;
            String source=sourceFor(sbn.getPackageName());
            if(!ExternalMessageStoreV249477.consent(this,source))return;
            String title=text(n.extras==null?new Bundle():n.extras,Notification.EXTRA_TITLE);
            String body=notificationBody(n);
            if(title.isEmpty()&&body.isEmpty())return;
            String id=stableId(sbn),pkg=sbn.getPackageName();
            JSONObject item=new JSONObject();
            item.put("id",id);item.put("source",source);item.put("package_name",pkg);item.put("app_label",appLabel(pkg));
            item.put("notification_key",sbn.getKey());item.put("notification_id",sbn.getId());item.put("notification_tag",String.valueOf(sbn.getTag()));
            item.put("title",title);item.put("body",body);item.put("created_at",sbn.getPostTime()>0?sbn.getPostTime():System.currentTimeMillis());
            item.put("posted_at",sbn.getPostTime());item.put("unread",true);item.put("item_type","notification");
            item.put("channel_id",Build.VERSION.SDK_INT>=26?String.valueOf(n.getChannelId()):"");
            ExternalMessageStoreV249477.put(this,item);
            OPEN_PACKAGES.put(id,pkg);
            if(n.contentIntent!=null)OPEN_ACTIONS.put(id,n.contentIntent);
            boolean mirror=getSharedPreferences("ok_ithaki_prefs",MODE_PRIVATE).getBoolean("ok_external_mirror_enabled_v249527",false);
            boolean master=getSharedPreferences("ok_ithaki_prefs",MODE_PRIVATE).getBoolean("ok_notifications_enabled_v249525",true);
            if(master&&mirror)mirror(id,source,title,body,n.contentIntent);
        }catch(Exception ignored){}
    }

    private void mirror(String id,String source,String title,String body,PendingIntent original){
        try{
            NotificationManager nm=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
            boolean withSound=getSharedPreferences("ok_ithaki_prefs",MODE_PRIVATE).getBoolean("ok_notification_sound_v249525",true);
            String channel=withSound?CH_SOUND:CH_SILENT;
            if(Build.VERSION.SDK_INT>=26){
                NotificationChannel ch=new NotificationChannel(channel,"OK ITHAKI · Εξωτερικές ειδοποιήσεις",withSound?NotificationManager.IMPORTANCE_DEFAULT:NotificationManager.IMPORTANCE_LOW);
                if(!withSound){ch.setSound(null,null);ch.enableVibration(false);} nm.createNotificationChannel(ch);
            }
            PendingIntent pi=original;
            if(pi==null){
                Intent i=new Intent(this,MainActivity.class).setAction("com.okithaki.OPEN_EXTERNAL_CENTER").putExtra("external_local_id",id).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);
                pi=PendingIntent.getActivity(this,id.hashCode(),i,PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_IMMUTABLE);
            }
            NotificationCompat.Builder nb=new NotificationCompat.Builder(this,channel).setSmallIcon(com.okithaki.autoapp.R.drawable.ic_launcher)
                    .setContentTitle("OK ITHAKI · "+source.toUpperCase(Locale.ROOT)+" · "+title)
                    .setContentText(body).setStyle(new NotificationCompat.BigTextStyle().bigText(body)).setAutoCancel(true).setContentIntent(pi);
            if(!withSound) nb.setSilent(true).setVibrate(new long[]{0L});
            nm.notify(id.hashCode(),nb.build());
        }catch(Exception ignored){}
    }

    private static boolean launchPackage(Context c,String pkg){
        if(pkg==null||pkg.trim().isEmpty())return false;
        try{Intent i=c.getPackageManager().getLaunchIntentForPackage(pkg);if(i!=null){i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);c.startActivity(i);return true;}}catch(Exception ignored){}
        return false;
    }

    public static boolean open(Context c,String id){
        try{PendingIntent p=OPEN_ACTIONS.get(id);if(p!=null){p.send();return true;}}catch(Exception ignored){}
        String pkg=OPEN_PACKAGES.get(id);
        if(pkg==null||pkg.trim().isEmpty()){
            try{pkg=ExternalMessageStoreV249477.find(c,id).optString("package_name","");}catch(Exception ignored){}
        }
        return launchPackage(c,pkg);
    }
}
