package services

import (
	"time"
	"ripple/config"
	"ripple/helpers"
)

const autoCancelInterval = 1 * time.Minute

func (pm *PaymentManager) AutoCancelRoutine() {
	now := time.Now()
	for paymentID, payment := range pm.st.Storage.Payments {
		if !payment.Committing() || !payment.CounterpartIn() || now.Sub(time.Unix(payment.CreatedAt, 0)) <= config.Timeout {
			continue
		}

        payment.Cancel()
        pm.st.Storage.Payments[paymentID] = payment
		pm.st.MustSave()
		pm.accSender.Send(payment.Outgoing, helpers.BuildCancelPayment(paymentID, payment.Preimage))
    }
}

func (pm *PaymentManager) RunAutoCancelRoutine() {
	for {
		pm.AutoCancelCh <- struct{}{}
		time.Sleep(autoCancelInterval)
	}
}