package common

import (
	"context"
	"sync"
)

type PauseSub struct {
	ctrl  *CtrlWait
	items []chan int8
	m     sync.RWMutex
}

func (p *PauseSub) GetNew() chan int8 {
	p.m.Lock()
	defer p.m.Unlock()
	sub := make(chan int8)
	p.items = append(p.items, sub)
	return sub
}

func (p *PauseSub) Close(sub chan int8) {
	p.m.Lock()
	defer p.m.Unlock()
	close(sub)
	for i, v := range p.items {
		if v == sub {
			p.items = append(p.items[:i], p.items[i+1:]...)
		}
	}
}

// Run 开始监听
func (p *PauseSub) Run(ctx context.Context) {
	p.ctrl.Open()
	defer p.ctrl.Close()

	for {
		select {
		case <-ctx.Done():
			return
		case c := <-p.ctrl.C:
			go func() {
				p.m.RLock()
				defer p.m.RUnlock()
				for _, item := range p.items {
					item <- c
				}
			}()
		}
	}
}

func NewPauseSub(c *CtrlWait) *PauseSub {
	return &PauseSub{
		ctrl:  c,
		items: make([]chan int8, 0),
	}
}
