import * as cornerstone from 'cornerstone-core'
var taskPool = [] // 请求池
let numRequest = 0 // 正在执行数量
const maxRequest = 4 // 可配置
let taskTimer // 轮询的定时器
var pendingList =[]
var cachedTask = {} // 存放的任务数据
const maxTask = 6


// 预加载池的添加
function addTaskIntoPool(task) {
  return new Promise((resolve, reject) => {
    taskPool.forEach(task=>{
      task.priority = task.priority
    })
    const cache = cachedTask[task.key]
    const callback = (executeRes) => {
      if (executeRes.success) {
        resolve(executeRes.res)
      } else {
        reject(executeRes.err)
      }
    }
    const priority = task.priority || 0;
    if (cache) {
      cache.priority = priority
      task.callback =callback
    } else {
      task.callback =callback
      cachedTask[task.key] = task
      taskPool.push(task)
    }
  })
}
// 执行下载
function executeTask() {
  if (taskPool.length > 0) {
    numRequest = 0
    const executeRequest = maxRequest - numRequest
    
    if (executeRequest > 0) {
      
      for (let i = 0; i < executeRequest; i++) {
        sortTaskPool()
       
        const task = taskPool.shift()
        if (!task) {
          return
        }
        numRequest++
        task.execute().then((res) => {
          numRequest--
          task.callback({ success: true, res })
          executeTask()
        }, (err) => {
          numRequest--
          task.callback({ success: false,err })
          executeTask()
        })
      }
    }
  }else{
    startTaskTimer()
  }
}
function sortTaskPool() {
  if (taskPool.length > 0) {
    taskPool.sort((a, b) =>  b.priority-a.priority )
    
  }
}

// 轮询检查请求池中是否有请求需要执行
function startTaskTimer() {
  if(taskTimer){
    clearInterval(taskTimer)
    taskTimer = null
  }
  taskTimer = setInterval(() => {
    if (taskPool.length > 0) {
      stopTaskTimer()
      executeTask()
    }else{
      return
    }
  }, 50)
}

// 停止轮询
function stopTaskTimer() {
  clearInterval(taskTimer)
  taskTimer = null
}
function loadAndCacheImagePlus(imageId,seriesId, priority) {
  return new Promise((resolve, reject) => {
    const imageLoadObject = cornerstone.imageCache.getImageLoadObject(imageId)
    if (imageLoadObject) {
      imageLoadObject.promise.then((image) => {
        resolve(image)
      }, (err) => {
        reject(err)
      })
    } else {
      const imageTask = buildImageRequestTask(imageId,seriesId, { priority })
      addTaskIntoPool(imageTask).then((res) => {
        resolve(res)
      }).catch(e => {
        reject(e)
      })
    }
  })
}
function removeTask(seriesId){
  stopTaskTimer()
  if (taskPool.length > 0) {
    for(var i =taskPool.length-1; i>=0;i--){
      if(taskPool[i] && taskPool[i].seriesId === seriesId){
        delete cachedTask[taskPool[i].key]
        taskPool.splice(i,1)
       
      }
    }
    
  }
  startTaskTimer()
}
function resetRequestPool(){
  taskPool = []
  pendingList =[]
  cachedTask = {}
}
function resetCachedTask(){
  taskPool = []
  pendingList =[]
  cachedTask = {}
}
function buildImageRequestTask(imageId,seriesId, config = {}) {
  return {
      key: imageId,
      seriesId:seriesId,
      ...config,
      execute: () => {
          return cornerstone.loadAndCacheImage(imageId)
      }
  };
}

export default {
  addTaskIntoPool,
  executeTask,
  startTaskTimer,
  stopTaskTimer,
  loadAndCacheImagePlus,
  removeTask,
  resetRequestPool,
  resetCachedTask
}
