package channel

import (
	plnModel "LAPP_ACURA_MOM_BACKEND/models/pln"
	"errors"
	"sync"
)

type ReleaseTaskChannel struct {
	c      chan plnModel.CustOrder
	closed bool
	mutex  sync.Mutex
}

func NewReleaseChannel() *ReleaseTaskChannel {
	return &ReleaseTaskChannel{
		c: make(chan plnModel.CustOrder, 100),
	}
}

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

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

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

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

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