package it.integry.integrywmsnative.core.context;

import android.content.Context;

import com.annimon.stream.Stream;
import com.google.firebase.crashlytics.FirebaseCrashlytics;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.DiskLogAdapter;
import com.orhanobut.logger.Logger;

import java.io.File;

import javax.inject.Inject;
import javax.inject.Singleton;

import it.integry.integrywmsnative.BuildConfig;
import it.integry.integrywmsnative.MainApplication;
import it.integry.integrywmsnative.core.data_store.db.AppDatabase;
import it.integry.integrywmsnative.core.settings.SettingsManager;
import it.integry.integrywmsnative.core.settings.Stash;
import it.integry.integrywmsnative.core.utility.UtilityContext;
import it.integry.integrywmsnative.core.utility.UtilityResources;
import it.integry.integrywmsnative.core.utility.UtilityString;
import it.integry.integrywmsnative.core.utility.UtilityToast;

@Singleton
public class AppContext {

    //Note: this is the Application Context NOT the Activity Context
    private final Context mApplicationContext;

    @Inject
    AppDatabase mAppDatabase;

    @Inject
    SettingsManager mSettingsManager;

    private File logsFolder;

    public AppContext(Context context) {
        this.mApplicationContext = context;

        MainApplication.appComponent
                .inject(this);
    }


    @Inject
    public void init() {
        this.initUtilities();

        this.initSettings();

        this.initCrashlytics();

        this.initLogger();
    }

    public File getLogFilePath() {
        return logsFolder;
    }


    private void initSettings() {
        Stash.init(mApplicationContext);
        mSettingsManager.init();
    }

    private void initCrashlytics() {
        if (!BuildConfig.DEBUG) {
            FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();

            if (SettingsManager.isInstanceAvailable() &&
                    (SettingsManager.i().getUserSession() != null && !UtilityString.isNullOrEmpty(SettingsManager.i().getUserSession().getProfileDB())) &&
                    (SettingsManager.i().getUser() != null && !UtilityString.isNullOrEmpty(SettingsManager.i().getUser().getFullname()))) {

                crashlytics.setUserId(SettingsManager.i().getUser().getFullname());
                crashlytics.setCustomKey("profile_db", SettingsManager.i().getUserSession().getProfileDB());
            }
        }
    }

    private void initUtilities() {
        UtilityContext.initApplicationContext(mApplicationContext);
        UtilityResources.init(mApplicationContext);
        UtilityToast.init(mApplicationContext);
    }

    private void initLogger() {
        Logger.addLogAdapter(new AndroidLogAdapter());

        logsFolder = new File(mApplicationContext.getExternalFilesDir(null).getAbsolutePath());
        int maxBytesSize = 5 * 1024 * 1024;
        Logger.addLogAdapter(new DiskLogAdapter(logsFolder, maxBytesSize));

        removeOldLogs(logsFolder);
    }

    private void removeOldLogs(File logsFolder) {
        var files = logsFolder.listFiles();

        if (files == null || files.length <= 1)
            return;

        var logFiles = Stream.of(files)
                .sortBy(x -> -1 * x.lastModified())
                .skip(1)
                .toList();

        for (var logFile : logFiles) {
            boolean isDeleted = logFile.delete();
        }

        files = logsFolder.listFiles();

        if (files == null || files.length > 1)
            return;

        final boolean isRenamed = files[0].renameTo(new File(files[0].getParentFile().getAbsolutePath() + "/" + "logs_0.csv"));

    }

}
