package com.xypower.frpandroid;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.util.Random;
import java.util.logging.Logger;

import org.jetbrains.annotations.NotNull;

public class ShellService extends Service {

    private static final String TAG = "FRP";

    private Thread mProcessThread;
    private final StringBuilder mOutputBuilder = new StringBuilder();
    private final LocalBinder mBinder = new LocalBinder();
    private final Random mGenerator = new Random();

    public Logger logger;

    public ShellService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // Intrinsics.checkNotNullParameter(intent, "intent");
        return (IBinder)this.mBinder;
    }

    @NotNull
    public final String getOutput() {
        return this.mOutputBuilder.toString();
        // Intrinsics.checkNotNullExpressionValue(var10000, "outputBuilder.toString()");
    }

    public final void clearOutput() {
        // StringsKt.clear(this.outputBuilder);
        // this.outputBuilder.
        this.mOutputBuilder.delete(0, mOutputBuilder.length());
    }

    public final int getRandomNumber() {
        return this.mGenerator.nextInt(100);
    }

    @Override
    public void onCreate() {
        super.onCreate();

        logger = Logger.getLogger("com.xypower.frp.logger");

        logger.info("ShellService is launching");
    }

    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        String fileName = "";

        File confFile = new File(getDataDir(), "conf");
        confFile = new File(confFile, "config.toml");

        if (this.mProcessThread != null) {
            Log.w("adx", "process isn't null,service won't start");
            return Service.START_NOT_STICKY;
        } else if (intent != null) {
            Bundle extras = intent.getExtras();
            fileName = extras != null ? extras.getString("filename") : null;
            if (TextUtils.isEmpty(fileName)) {
                logger.warning("Filename is null");
                throw new NullPointerException("null cannot be cast to non-null type kotlin.String");
            } else {

                ApplicationInfo applicationInfo = null;
                try {
                    applicationInfo = this.getPackageManager().getApplicationInfo(this.getPackageName(), PackageManager.GET_SHARED_LIBRARY_FILES);
                } catch (Exception ex) {

                }
                // Intrinsics.checkNotNullExpressionValue(var9, "packageManager.getApplic…GET_SHARED_LIBRARY_FILES)");
                Log.d("adx", "native library dir " + applicationInfo.nativeLibraryDir);

                logger.warning("Starting service");
                try {
                    String cmd = applicationInfo.nativeLibraryDir + '/' + fileName + " -c " + confFile.getAbsolutePath();
                    String[] params = new String[]{""};
                    File workDir = this.getFilesDir();
                    // Intrinsics.checkNotNullExpressionValue(var10003, "this.filesDir");
                    this.runCommand(cmd, params, workDir);
                } catch (Exception ex) {
                    // Log.e("adx", ExceptionsKt.stackTraceToString((Throwable)var7));
                    logger.warning(ex.getMessage());
                    ex.printStackTrace();
                    // Toast.makeText((Context)this, (CharSequence)ex.getMessage(), Toast.LENGTH_SHORT).show();
                    this.stopSelf();
                    return Service.START_NOT_STICKY;
                }

                logger.warning("Service has been started");
                // Toast.makeText((Context)this, (CharSequence)"已启动frp服务", Toast.LENGTH_SHORT).show();
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    this.startForeground(1, this.showNotification());
                }
                return Service.START_NOT_STICKY;
            }
        } else {
            fileName = "Error:filename unknown!!!";
            Log.e("adx", fileName);
            // Toast.makeText((Context)this, (CharSequence)fileName, Toast.LENGTH_SHORT).show();
            this.stopSelf();
            return Service.START_NOT_STICKY;
        }
    }

    public void onDestroy() {
        try {
            if (mProcessThread != null) {
                mProcessThread.interrupt();
            }

            logger.warning("Service has been stopped");
            // Toast.makeText((Context)this, (CharSequence)"已关闭frp服务", Toast.LENGTH_SHORT).show();
        } catch (Exception ex) {

        }
    }

    private final void runCommand(String command, String[] envp, File dir) {
        mProcessThread = new ShellThread(command, envp, dir, new ShellThread.Function1() {

            @Override
            public Object invoke(Object var1) {
                this.invoke((String)var1);
                return null;
                // return Unit.INSTANCE;
            }

            public final void invoke(@NotNull String it) {
                // Intrinsics.checkNotNullParameter(it, "it");
                ShellService.this.mOutputBuilder.append(it + "\n");
            }
        });

        if (mProcessThread != null) {
            mProcessThread.start();
        }

    }

    private final Notification showNotification() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            Intent intent = new Intent(this.getApplicationContext(), MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity((Context) this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
            Notification.Builder notificationBuilder = new Notification.Builder((Context) this, "shell_bg");

            notificationBuilder.setSmallIcon(R.drawable.ic_launcher_foreground).
                    setContentTitle((CharSequence) "frp后台服务").
                    setContentText((CharSequence) "已启动frp").
                    setContentIntent(pendingIntent);
            return notificationBuilder.build();
        }

        return null;
    }

    public final class LocalBinder extends Binder implements IBinder {
        @NotNull
        public final ShellService getService() {
            return ShellService.this;
        }
    }


}