import BackgroundService from "react-native-background-actions";
import { BackgroundDocumentLast } from "./BackgroundDocumentLast";
import { UELogEvent } from "react-native-digitcamera/src/common/libEventLog/UserExperior/LibUserExperior";
import NetInfo from "@react-native-community/netinfo";
import CONFIGS from "./NotificationsConfig";

// Background task should be function which has a promise
// resolve() & reject() - stops the background action
export const createPromisifiedTask = (uploadTask) => {
  return async () => {
    await new Promise(async (resolve, reject) => {
      await uploadTask(resolve, reject);
    });
  };
};

/*
 - starts the background process
 - for the provided 'promisifiedTask'
 - promisifiedTask - async function to execute in background
 - initialNotificationConfig - default notification settings
*/
export const startBackgroundProcess = async (
  promisifiedTask,
  initialNotificationConfig
) => {
  console.log(
    "[INFO] . BackgroundTasks . startBackgroundProcess() execution started"
  );
  UELogEvent("[BACKGROUND] [TASK STARTED]");
  try {
    await BackgroundService.start(promisifiedTask, initialNotificationConfig);
  } catch (e) {
    UELogEvent("[BACKGROUND] [TASK ERROR]");
    console.log(
      "[ERROR] . BackgroundTasks . startBackgroundProcess() threw error - ",
      e.message
    );
  }
};

/*
 - updates the notification with provided progressObject in background
 - change below method name
*/
export const updateProgressNotification = async (progressObject) => {
  if (BackgroundService.isRunning()) {
    if (progressObject) {
      // console.log(
      //   "[INFO] . BackgroundTasks . updateUploadProgressInBackground() - progressObject",
      //   JSON.stringify(progressObject, null, "  ")
      // );
      try {
        // console.log(
        //   "[INFO] . BackgroundTasks . updateUploadProgressInBackground() execution started"
        // );
        await BackgroundService.updateNotification(progressObject);
      } catch (e) {
        console.log(
          "[ERROR] . BackgroundTasks . updateUploadProgressInBackground() threw error - ",
          e.message
        );
      }
    } else {
      console.log(
        "[ERROR] . BackgroundTasks . updateUploadProgressInBackground()  Undefined OR Null Values Passed - progressObject: ",
        progressObject
      );
    }
  } else {
    console.log(
      "[ERROR] . BackgroundTasks . updateUploadProgressInBackground() . Error - Background service is not running."
    );
    return;
  }
};

// To update notification with custom message
// before stopping the process
export const updateTextNotification = async (updateObj) => {
  // Run this if BackgroundService is running
  if (BackgroundService.isRunning()) {
    if (updateObj) {
      // console.log(
      //   "[INFO] . BackgroundTasks . runBeforeStop() . new updateObj: ",
      //   updateObj
      // );
      try {
        // console.log(
        //   "[INFO] . BackgroundTasks . runBeforeStop() execution started"
        // );
        // send progressBar:{} to de-render or hide the progress bar
        // so that taskDesc is visible
        await BackgroundService.updateNotification({
          ...updateObj,
          progressBar: {},
        });
      } catch (e) {
        console.log(
          "[ERROR] . BackgroundTasks . runBeforeStop() threw error - ",
          e.message
        );
      }
    } else {
      console.log(
        "[ERROR] . BackgroundTasks . runBeforeStop() Undefined OR Null Value Passed - message: ",
        message
      );
      return;
    }
  }
  // Otherwise
  else {
    console.log(
      "[ERROR] . BackgroundTasks . runBeforeStop() . Error - Background service is not running."
    );
    throw new Error("Background service is not running");
  }
};

//stopNotification - resolve function of executed promisified background task
export const runAfterSuccessUpload = async (stopNotification) => {
  try {
    BackgroundDocumentLast(stopNotification);
  } catch (e) {
    console.log(
      "[ERROR] . BackgroundTasks . stopSuccessfulBackgroundProcess() threw error -",
      e.message
    );
  }
};

// Stops background process
export const stopBackgroundProcess = async () => {
  try {
    console.log(
      "[INFO] . BackgroundTasks . stopBackgroundProcess() execution started"
    );
    await BackgroundService.stop();
  } catch (e) {
    console.log(
      "[ERROR] . BackgroundTasks . stopBackgroundProcess() threw error - ",
      e.message
    );
  }
};
