package channel

import (
	"errors"
	"sync"
)

type TaskChannel struct {
	name string
	c      chan interface{}
	closed bool
	mutex  sync.Mutex
}

func NewTaskChannel(name string) *TaskChannel {
	return &TaskChannel{
		c: make(chan interface{}, 100),
		name: name,
	}
}

// IsClosed 判断channel是否关闭
func (c *TaskChannel) IsClosed() bool {
	c.mutex.Lock()
	defer c.mutex.Unlock()
	return c.closed
}

// SendData 发送数据
func (c *TaskChannel) SendData(data interface{}) error {
	c.mutex.Lock()
	defer c.mutex.Unlock()
	if c.closed {
		return errors.New("管道已关闭")
	}
	c.c <- data
	return nil
}

func (c *TaskChannel) Close() {
	c.mutex.Lock()
	defer c.mutex.Unlock()
	if c.closed {
		return
	}
	close(c.c)
	c.closed = true
}

func (c *TaskChannel) Read() (data interface{}, ok bool, err error) {
	c.mutex.Lock()
	if c.closed {
		err = errors.New("管道已关闭")
		return
	}
	c.mutex.Unlock()
	data, ok = <- c.c
	return
}

func (c *TaskChannel) ResetChannel() (err error) {
	c.mutex.Lock()
	defer c.mutex.Unlock()
	if !c.closed {
		err = errors.New("管道未关闭")
		return
	}
	c.closed = false
	c.c = make(chan interface{}, 50)
	return
}