package it.integry.integrywmsnative.core.utility;

import com.orhanobut.logger.Logger;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.REST.consumers.SystemRESTConsumer;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.settings.SettingsManager;

public class UtilityLogger {

    public static void logMe(String message){
        StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();

        String caller = "UtilityLogger";

        for(int i = 0; i < stackTraceElements.length; i++){

            if(stackTraceElements[i].getMethodName().equalsIgnoreCase("logMe")){
                caller = stackTraceElements[i+1].getFileName() + "->" + stackTraceElements[i+1].getMethodName();
            }

        }

        Logger.d(message);
    }

    public static void errorMe(Exception ex) {
        errorMe(ex, null, null);
    }

    public static void errorMe(Exception ex, Runnable onComplete, RunnableArgs<Exception> onFailed) {
        String message = UtilityResources.readRawTextFile(R.raw.error_mail);

        message = message.replace("#exception_name#", ex.getMessage());

        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        message = message.replace("#stacktrace#", sw.toString());

        String currentAzienda = UtilityString.isNullOrEmpty(SettingsManager.i().userSession.profileDB) ? "" : SettingsManager.i().userSession.profileDB;
        message = message.replace("#azienda_nome#", currentAzienda);

        SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
        message = message.replace("#current_date#", sdf.format(new Date()));

        SystemRESTConsumer.sendErrorLogMail(message, onComplete, onFailed);
    }

}
