/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

package org.libreoffice.kit;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.res.AssetManager;
import android.util.Log;

import java.nio.ByteBuffer;

// Native methods in this class are all implemented in
// sal/android/lo-bootstrap.c as the lo-bootstrap library is loaded with
// System.loadLibrary() and Android's JNI works only to such libraries, it
// seems.
public final class LibreOfficeKit
{
    private static String LOGTAG = LibreOfficeKit.class.getSimpleName();
    private static AssetManager mgr;

    // private constructor because instantiating would be meaningless
    private LibreOfficeKit() {
    }

    // Trigger library initialization - as this is done automatically by executing the "static" block, this method remains empty. However we need this to manually (at the right time) can force library initialization.
    public static void initializeLibrary() {
    }

    // Trigger initialization on the JNI - LOKit side.
    private static native boolean initializeNative(String dataDir, String cacheDir, String apkFile, AssetManager mgr);

    public static native ByteBuffer getLibreOfficeKitHandle();

    // Wrapper for putenv()
    public static native void putenv(String string);

    // A method that starts a thread to redirect stdout and stderr writes to
    // the Android logging mechanism, or stops the redirection.
    public static native void redirectStdio(boolean state);

    static boolean initializeDone = false;

    // This init() method should be called from the upper Java level of
    // LO-based apps.
    // Mkoma: takes any Context (Mkoma starts the engine in a Service in its own process), not only an Activity.
    public static synchronized void init(Context context)
    {
        if (initializeDone) {
            return;
        }

        mgr = context.getResources().getAssets();

        ApplicationInfo applicationInfo = context.getApplicationInfo();
        String dataDir = applicationInfo.dataDir;
        Log.i(LOGTAG, String.format("Initializing LibreOfficeKit, dataDir=%s\n", dataDir));

        redirectStdio(true);

        String cacheDir = context.getApplicationContext().getCacheDir().getAbsolutePath();
        String apkFile = engineApk(context);

        if (!initializeNative(dataDir, cacheDir, apkFile, mgr)) {
            Log.e(LOGTAG, "Initialize native failed!");
            return;
        }
        initializeDone = true;
    }

    /**
     * Mkoma: the APK that holds the engine's resources. LibreOffice lists its resource folders by reading this one file
     * (lo_apk_opendir in sal/android/lo-bootstrap.c; files themselves are opened through the AssetManager, which sees
     * every split). In a Play bundle they are in the on-demand office_engine module: installed by Android (a split APK
     * of the app) or, before the app restarts after Play downloaded it, kept by SplitCompat in the app's files. In an
     * APK with the whole engine inside, they are in the base APK.
     */
    static String engineApk(Context context) {
        ApplicationInfo info = context.getApplicationInfo();
        if (info.splitSourceDirs != null) {
            for (String split : info.splitSourceDirs) {
                if (isEngineResources(new java.io.File(split).getName())) return split;
            }
        }
        java.io.File emulated = findEmulatedSplit(new java.io.File(context.getFilesDir(), "splitcompat"));
        if (emulated != null) return emulated.getAbsolutePath();
        return context.getApplicationContext().getPackageResourcePath();
    }

    private static java.io.File findEmulatedSplit(java.io.File dir) {
        java.io.File[] children = dir.listFiles();
        if (children == null) return null;
        for (java.io.File child : children) {
            if (child.isDirectory()) {
                java.io.File found = findEmulatedSplit(child);
                if (found != null) return found;
            } else if (isEngineResources(child.getName())) {
                return child;
            }
        }
        return null;
    }

    /** The module's own APK ("split_office_engine.apk"), not its per-device ones ("….config.x86_64.apk": libraries). */
    private static boolean isEngineResources(String name) {
        return name.contains("office_engine") && name.endsWith(".apk") && !name.contains(".config.");
    }

    // Now with static loading we always have all native code in one native
    // library which we always call liblo-native-code.so, regardless of the
    // app. The library has already been unpacked into /data/data/<app
    // name>/lib at installation time by the package manager.
    // Mkoma: loaded by an explicit call with a Context instead of a static block, because in Play bundles the libraries
    // come in an on-demand module (Play Feature Delivery) and are found through that Context; call it before anything
    // else here. A failure (an UnsatisfiedLinkError) leaves the class usable for a later attempt.
    public static void loadLibraries(Context context) {
        NativeLibLoader.load(context);
    }
}

class NativeLibLoader {
        private static boolean done = false;

        protected static synchronized void load(Context context) {
            if (done)
                return;
            // Mkoma: through SplitInstallHelper, which finds a library in the base app or in an installed on-demand
            // module (also one bundletool's local testing installed); the order is the libraries' dependency order.
            String[] libraries = {
                "nspr4", "plds4", "plc4", "nssutil3", "freebl3",
                // Mkoma: the engine's own SQLite is renamed (office_engine/spike/unpack_engine.py), as the app has its own.
                "losqlit",
                "softokn3", "nss3", "nssckbi", "nssdbm3", "smime3", "ssl3",
                "c++_shared", "lo-native-code",
            };
            for (String library : libraries) {
                com.google.android.play.core.splitinstall.SplitInstallHelper.loadLibrary(context, library);
            }
            done = true;
        }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
