
// logger provides a logger to log Seekia client events
// These logs are able to be viewed through the GUI

package logger

// Log types:
//	-General
//	-Network
//	-BackgroundJobs

//TODO: Add more log entries for events that should not happen, but may happen very rarely.
// We want to see if these kinds of events are happening more often than they should (almost never)
// There are also many other places where we should add logging

// TODO: Add automatic clearing of old logs, and a button to clear logs
// Also, a way to disable logging

import "seekia/internal/helpers"
import "seekia/internal/myDatastores/myList"

import "time"
import "errors"

var myLogListDatastore_General *myList.MyList
var myLogListDatastore_Network *myList.MyList
var myLogListDatastore_BackgroundJobs *myList.MyList

func getMyLogListDatastore(logsType string)(*myList.MyList, error){

	if (logsType == "General"){
		return myLogListDatastore_General, nil
	}
	if (logsType == "Network"){
		return myLogListDatastore_Network, nil
	}
	if (logsType == "BackgroundJobs"){
		return myLogListDatastore_BackgroundJobs, nil
	}

	return nil, errors.New("getMyLogListDatastore called invalid logsType: " + logsType)
}

// This function must be called whenever an app user signs in
func InitializeMyLogDatastores()error{

	newMyLogListDatastore_General, err := myList.CreateNewList("GeneralLog")
	if (err != nil) { return err }	

	newMyLogListDatastore_Network, err := myList.CreateNewList("NetworkLog")
	if (err != nil) { return err }

	newMyLogListDatastore_BackgroundJobs, err := myList.CreateNewList("BackgroundJobsLog")
	if (err != nil) { return err }

	myLogListDatastore_General = newMyLogListDatastore_General
	myLogListDatastore_Network = newMyLogListDatastore_Network
	myLogListDatastore_BackgroundJobs = newMyLogListDatastore_BackgroundJobs

	return nil	
}

func GetLogList(logsType string)([]string, error){

	logListDatastore, err := getMyLogListDatastore(logsType)
	if (err != nil) { return nil, err }

	logList, err := logListDatastore.GetList()
	if (err != nil) { return nil, err }

	return logList, nil
}

func AddLogError(logName string, logError error)error{

	errorString := "ERROR: " + logError.Error()
	
	err := AddLogEntry(logName, errorString)
	if (err != nil) { return err }	

	return nil
}

func AddLogEntry(logsType string, logEntry string)error{

	currentYear, currentMonth, currentDay := time.Now().Date()

	currentYearString := helpers.ConvertIntToString(currentYear)
	currentMonthString := helpers.ConvertIntToString(int(currentMonth))
	currentDayString := helpers.ConvertIntToString(currentDay)

	logEntryWithTime := currentYearString + "-" + currentMonthString + "-" + currentDayString + ": " + logEntry

	myLogListDatastore, err := getMyLogListDatastore(logsType)
	if (err != nil) { return err }

	err = myLogListDatastore.AddListItem(logEntryWithTime)
	if (err != nil) { return err }

	return nil
}


