package main

import (
	"log"
	"strings"

	"github.com/distatus/battery"
	hcron "github.com/lnquy/cron"
)

var cronDescriptor, _ = hcron.NewDescriptor()

func describeCron(expr string) string {
	desc, err := cronDescriptor.ToDescription(expr, hcron.Locale_en)
	if err != nil {
		return expr
	}
	desc = strings.TrimSpace(desc)
	if len(desc) > 0 {
		desc = strings.ToLower(desc[:1]) + desc[1:]
	}
	return desc
}

func onBatteryPower() bool {
	b, err := battery.Get(0)
	if _, ok := err.(battery.ErrFatal); ok {
		return false
	}
	if b == nil {
		return false
	}
	return b.State.Raw == battery.Discharging
}

func schedulePausedForBattery(prof Profile) bool {
	return !prof.Schedule.OnBattery && onBatteryPower()
}

func runScheduleCallback(key stateKey, onDone func(), run func(Config, int, Profile)) {
	name := string(key)
	defer func() {
		if r := recover(); r != nil {
			log.Printf("[%s] scheduled run panicked: %v", name, r)
		}
	}()

	cfg := loadConfig()
	idx, prof, err := resolveProfileIndex(cfg, key)
	if err != nil {
		log.Printf("[%s] skipping scheduled run: %v", name, err)
		return
	}
	name = prof.displayName()
	if schedulePausedForBattery(prof) {
		log.Printf("[%s] skipping scheduled run: on battery power", name)
		return
	}
	if !acquireProfile(key) {
		log.Printf("[%s] skipping scheduled run: profile already busy", name)
		return
	}
	if onDone != nil {
		defer onDone()
	}
	defer releaseProfile(key)
	run(cfg, idx, prof)
}
