package sqlAsyncMgr

import (
	"fmt"

	"github.com/jinzhu/gorm"
	"goutil/logUtil"
	"goutil/stringUtil"
)

type SqlAsyncWorkerPool struct {
	// 工作者数量
	wcount int32

	// 工作者列表
	workers []*SqlAsyncWorker
}

// newSqlAsyncWorkerPool 构造同步池
func newSqlAsyncWorkerPool(workerCount int32, _flushCallBack func(*SqlAsyncItemModel), _logAction func(logUtil.LogType, string), _getSyncName func() string, db *gorm.DB) *SqlAsyncWorkerPool {
	result := &SqlAsyncWorkerPool{
		wcount:  workerCount,
		workers: make([]*SqlAsyncWorker, workerCount, workerCount),
	}

	var i int32
	for i = 0; i < workerCount; i++ {
		newWorker := newSqlAsyncWorker(i, _flushCallBack, _logAction, _getSyncName, db)
		result.workers[i] = newWorker
	}

	return result
}

// Start 启动
func (this *SqlAsyncWorkerPool) Start() {
	for _, w := range this.workers {
		w.Start()
	}
}

// Stop 停止工作
func (this *SqlAsyncWorkerPool) Stop() []*SqlAsyncItemModel {
	result := make([]*SqlAsyncItemModel, 0)
	for _, w := range this.workers {
		if tempList := w.Stop(); tempList != nil {
			result = append(result, tempList...)
		}
	}

	return result
}

// GetWork 获取指定work
func (this *SqlAsyncWorkerPool) GetWork(tableName string) (*SqlAsyncWorker, error) {
	index := stringUtil.HashCode(tableName) % int(this.wcount)
	if index < 0 || index >= int(this.wcount) {
		return nil, fmt.Errorf("SqlAsyncWorkerPool中work数量为:%v,不存在id=%v的worker", this.wcount, index)
	}

	return this.workers[index], nil
}

// GetWaitSyncCount 获取待同步的sql数量
func (this *SqlAsyncWorkerPool) GetWaitSyncCount() int32 {
	var count int32
	for _, w := range this.workers {
		count = count + w.WaitSqlCount()
	}

	return count
}
