package channel

import "sync"

// Closed 可包含关闭状态的通道
type Closed[T any] struct {
	ch     chan T
	closed bool
	mu     sync.RWMutex
}

func (s *Closed[T]) Close() {
	s.mu.Lock()
	defer s.mu.Unlock()

	if s.closed {
		return
	}

	close(s.ch)
	s.closed = true

	return
}

func (s *Closed[T]) Data() <-chan T {
	return s.ch
}

func (s *Closed[T]) Send(data T) bool {
	s.mu.RLock()
	defer s.mu.RUnlock()

	if s.closed {
		return false
	}

	s.ch <- data

	return true
}

func (s *Closed[T]) isClosed() bool {
	s.mu.RLock()
	defer s.mu.RUnlock()

	return s.closed
}

func NewClosed[T any]() *Closed[T] {
	return &Closed[T]{
		ch: make(chan T),
	}
}
