package cron_jobs

import (
	b64 
	

	
	
	
	
	
	
	
	
	
)

// RegisterAndRun registers and runs new cron job
func ( *models.CronJob) error {
	,  := constants.GLOBAL_SCHEDULER.Tag(.ID.String()).Every(1).Week().Weekday(time.Weekday(.Day)).At(.Time).Do(func() {
		// Update cronjob as processing
		.UpdateAsProcessing()
		// Get extension
		,  := liman.GetExtension(&models.Extension{
			ID: .ExtensionID.String(),
		})
		if  != nil {
			// Update job as failed
			.UpdateAsFailed(.Error())
			return
		}
		// Check extension status
		if .Status == "0" {
			// Update job as failed
			.UpdateAsFailed("extension is unavailable")
			return
		}

		// Get credentials
		 := &models.Credentials{}
		if .RequireKey == "true" {
			,  = liman.GetCredentials(
				&models.User{
					ID: .UserID.String(),
				},
				&models.Server{
					ID: .ServerID.String(),
				},
			)
			// Check errors and username is valid
			if  != nil || len(.Username) < 1 {
				// Update job as failed
				.UpdateAsFailed("you need a key to use this extension")
				return
			}
		}

		// Encode to b64 and set as form value
		 := make(map[string]string)
		["data"] = b64.StdEncoding.EncodeToString([]byte(.Payload))

		// Generate token for user
		,  := user_token.Create(.UserID.String())
		if  != nil {
			.UpdateAsFailed(.Error())
			return
		}

		// Generate new id for logs
		 := uuid.New()

		// Generate command
		,  := sandbox.GenerateCommand(
			,
			,
			&models.CommandParams{
				TargetFunction: .Target,
				Locale:         helpers.Env("APP_LANG", "tr"),
				Extension:      .ExtensionID.String(),
				Server:         .ServerID.String(),
				User:           .UserID.String(),
				LogID:          .String(),
				RequestData:    ,
				BaseURL:        .BaseURL,
				Token:          ,
			},
		)
		if  != nil {
			// Update job as failed
			.UpdateAsFailed(.Error())

			return
		}

		 := linux.Execute()
		.UpdateAsDone()
	})
	if  != nil {
		return 
	}

	constants.GLOBAL_SCHEDULER.StartAsync()

	return nil
}

// Delete deletes specified job from scheduler
func ( *uuid.UUID) error {
	// Remove cronjob from global scheduler
	if  := constants.GLOBAL_SCHEDULER.RemoveByTag(.String());  != nil {
		return 
	}

	return nil
}

// InitCronJobs inits all cronjobs
func () error {
	var  []*models.CronJob
	if  := database.Connection().Find(&).Error;  != nil {
		return 
	}

	for ,  := range  {
		if  := RegisterAndRun();  != nil {
			.UpdateAsFailed(.Error())
		}
	}

	return nil
}