var express = require('express');
var router = express.Router();
const { spawn } = require('child_process');
const fs = require("fs");

const method = require("../config/method")
const config = require("../config/config")

const { GETCLASSURL, GETCLASSURLPARAMETER, PROJECTCATALOG, PROJECTWINCATALOG, BACKMEDIACONFIG } = config
const { YesterdayTime, getRequestClassIds } = method

const { startTime, endTime } = YesterdayTime()
let siteIds = GETCLASSURLPARAMETER.siteId

let classid = []
let className = ""

/**
 * 
 * @param {*} id 课堂id
 */
function mediaCreat(id) {
  let mediaDir = PROJECTCATALOG+"/media/"
  let dir = PROJECTCATALOG+"/media/"+className
  if (!fs.existsSync(mediaDir)){
    fs.mkdirSync(mediaDir);
  }
  if (!fs.existsSync(dir)){
    fs.mkdirSync(dir);
  }
  let url = `web_capture_c -o=../media/${className}/${id}.mp4 -u="${BACKMEDIACONFIG.url}?classId=${id}&userId=${BACKMEDIACONFIG.userId}&userName=${BACKMEDIACONFIG.userName}&userRole=${BACKMEDIACONFIG.userRole}&portalIP=${BACKMEDIACONFIG.portalIP}&portalPort=${BACKMEDIACONFIG.portalPort}&channels=${BACKMEDIACONFIG.channels}&playRecord=${BACKMEDIACONFIG.playRecord}" -d=${BACKMEDIACONFIG.d} -s=${BACKMEDIACONFIG.s} -fa=${BACKMEDIACONFIG.fa}`
  var workerProcess = spawn(url, { cwd: PROJECTWINCATALOG, shell: true })
  workerProcess.stdout.on('data', async function (data) {
    if(classid.length){
      let id = classid.shift()
      mediaCreat(id['classId'])
    }else{
      if (siteIds.length) {
        // 如果有多家需要录制,继续录制下一家
        className = siteIds.shift()
        let result = await getRequestClassIds(GETCLASSURL, className, GETCLASSURLPARAMETER.key, startTime, endTime)
        if (result.data && result.data.code == 0) {
          // 返回成功
          classid = result.data.data.list
          if(classid.length){
            let id = classid.shift()
            mediaCreat(id['classId'])
          }
        }
      }
    }
  });
  //  workerProcess.stderr.on('data', function (data) {
  //     console.log('stderr: ' + data);
  //  });

  //  workerProcess.on('close', function (code) {
  //     console.log('子进程已退出,退出码 '+code);
  //  });
}

router.get('/', async function (req, res, next) {
  className = siteIds.shift()
  let result = await getRequestClassIds(GETCLASSURL, className, GETCLASSURLPARAMETER.key, startTime, endTime)
  if (result.data && result.data.code == 0) {
    // 成功
    classid = result.data.data.list
      if (classid.length) {
        for (let i = 0; i < 10; i++) {
          let id = classid.shift()
          if (id) {
            mediaCreat(id['classId'])
          }else{
            return false
          }
        }
      }
  }
  res.render('index', { title: 'Express' });
});

module.exports = router;