var express = require('express');
var url = require('url');
var router = express.Router();

var ljConst =  require("../common/LjConst");
var ljRetState =  require("../common/LjRetState");

var logHelper = require("../helper/LjLogHelper.js");
var httpHelper = require("../helper/LjHttpHelper");
var fileHelper = require("../helper/LjFileHelper");
var apiHelper = require("../helper/LjApiHelper");
var ljStringHelper = require("../helper/LjStringHelper");

/**
 * 下载文件
 */
router.get("/downloadFile",function(req,res,next)
{
    var arg = url.parse(req.url, true).query;
    var courseId = arg.courseId;
    var eid = arg.eid;
    var uid = arg.uid;
    var token = arg.token;
    var lessonId = arg.lessonId;
    //获取参数
    logHelper.debug(arg);

    //校验参数
    if (ljStringHelper.isNull(courseId))
    {
        logHelper.info("null object of courseId");

        ljRetState.code = 2;
        ljRetState.msg ="null object of courseId"
        res.json(ljRetState);

        return;
    }
    if (ljStringHelper.isNull(lessonId))
    {
        logHelper.info("null object of lessonId");

        ljRetState.code = 2;
        ljRetState.msg ="null object of lessonId"
        res.json(ljRetState);

        return;
    }
    if (ljStringHelper.isNull(eid))
    {
        logHelper.info("null object of eid");

        ljRetState.code = 2;
        ljRetState.msg ="null object of eid"
        res.json(ljRetState);

        return;
    }
    if (ljStringHelper.isNull(uid))
    {
        logHelper.info("null object of uid");

        ljRetState.code = 2;
        ljRetState.msg ="null object of uid"
        res.json(ljRetState);

        return;
    }
    if (ljStringHelper.isNull(token))
    {
        logHelper.info("null object of token");

        ljRetState.code = 2;
        ljRetState.msg ="null object of token"
        res.json(ljRetState);

        return;
    }

    var opt = {};
    opt.eid = eid;
    opt.uid = uid;
    opt.token = token;
    opt.lessonId = lessonId;
    opt.courseId = courseId;
    opt.path = "/lesson/" + opt.lessonId;
    opt.url = apiHelper.getApiForQueryCourse(opt.lessonId, opt.courseId, opt.eid);
    opt.method = "get";

    httpHelper.request(opt, function (error, res, body)
    {
        //开始下载
        opt.downloadStatus = ljConst.FILE_DOWNLOADING
        addDownload(opt);
        logHelper.info("Begin to download file with lessonId【"+opt.lessonId+"】");

        let obj = JSON.parse(body);

        var lessonJsonObj = JSON.parse(body);
        if (lessonJsonObj.code == 200)
        {
            /*课件-Begin*/
            //课程集合
            var courseList = lessonJsonObj.data.list;
            //课程数
            var courseListSize = courseList.length;
            //遍历课件
            for (var i = 0; i < courseListSize; i++)
            {
                //资源集合
                var resourceList = courseList[i].list;

                //资源数
                var resourceSize = resourceList.length;

                for (var j = 0; j < resourceSize; j++)
                {
                    logHelper.debug(resourceList[j].url);
                    var url = resourceList[j].url;
                    fileHelper.downloadFile(url);
                    if(resourceSize - 1 == j)
                    {
                        //下载完成
                        opt.downloadStatus = ljConst.FILE_DOWNLOADED
                        addDownload(opt);
                        logHelper.info("End to download file with lessonId【"+opt.lessonId+"】");
                    }
                }
            }
            /*课件-End*/

            return "ok";
        }
        else
        {
            logHelper.error("failed to query lesson with lessonId[" + opt.lessonId + "],caused by error:" + lessonJsonObj);
            return "error";
        }
    })

    ljRetState.code = 2;
    ljRetState.msg ="null object of uid"
    ljRetState.success = true;
    res.setHeader("Access-Control-Allow-Origin","*");
    res.json(ljRetState);

    return;
});

/**
 * 读取文件
 */
router.get("/readFile",function(req,res)
{
    var arg = url.parse(req.url, true).query;
    var fileDirStr = arg.n;
    var fileDirNew =  fileDirStr.replace(/\*/g,'\\');
    
    var fileDir =  fileHelper.getFileDir(fileDirNew)
    var fileProp =  fileHelper.getFileProperty(fileDir);

    logHelper.info(fileProp.fileType);
    if(fileProp.fileType == ljConst.VIDEO_TYPE_MP4)
    {
        logHelper.info(fileDir);
        fileHelper.readDecryptedStream(res,fileDir,"video/mp4")
    }
    else
    {
        fileHelper.readDecryptedStream(res,fileDir,"image/jpeg")
    }
});
function test()
{
    console.log(11);
}
/**
 * 删除下载文件
 */
router.get("/delFile",function(req,res)
{
    var arg = url.parse(req.url, true).query;
    var courseId = arg.courseId;
    var eid = arg.eid;
    var uid = arg.uid;
    var token = arg.token;
    var lessonId = arg.lessonId;
    //获取参数
    logHelper.debug(arg);

    //校验参数
    if (ljStringHelper.isNull(courseId))
    {
        logHelper.info("null object of courseId");

        ljRetState.code = 2;
        ljRetState.msg ="null object of courseId"
        res.json(ljRetState);

        return;
    }
    if (ljStringHelper.isNull(lessonId))
    {
        logHelper.info("null object of lessonId");

        ljRetState.code = 2;
        ljRetState.msg ="null object of lessonId"
        res.json(ljRetState);

        return;
    }
    if (ljStringHelper.isNull(eid))
    {
        logHelper.info("null object of eid");

        ljRetState.code = 2;
        ljRetState.msg ="null object of eid"
        res.json(ljRetState);

        return;
    }
    if (ljStringHelper.isNull(uid))
    {
        logHelper.info("null object of uid");

        ljRetState.code = 2;
        ljRetState.msg ="null object of uid"
        res.json(ljRetState);

        return;
    }
    if (ljStringHelper.isNull(token))
    {
        logHelper.info("null object of token");

        ljRetState.code = 2;
        ljRetState.msg ="null object of token"
        res.json(ljRetState);

        return;
    }

    var opt = {};
    opt.eid = eid;
    opt.uid = uid;
    opt.token = token;
    opt.lessonId = lessonId;
    opt.courseId = courseId;
    opt.path = "/lesson/" + opt.lessonId;
    opt.url = apiHelper.getApiForQueryCourse(opt.lessonId, opt.courseId, opt.eid);
    opt.method = "get";

    httpHelper.request(opt, function (error, res, body)
    {
        let obj = JSON.parse(body);

        var lessonJsonObj = JSON.parse(body);
        if (lessonJsonObj.code == 200)
        {
            /*课件-Begin*/
            //课程集合
            var courseList = lessonJsonObj.data.list;
            //课程数
            var courseListSize = courseList.length;
            //遍历课件
            for (var i = 0; i < courseListSize; i++)
            {
                //资源集合
                var resourceList = courseList[i].list;

                //资源数
                var resourceSize = resourceList.length;

                for (var j = 0; j < resourceSize; j++)
                {
                    logHelper.debug(resourceList[j].url);
                    var url = resourceList[j].url;
                    fileHelper.downloadFile(url)
                }
            }
            /*课件-End*/

            //删除记录
            delDownload(opt);
            return "ok";
        }
        else
        {
            logHelper.error("failed to query lesson with lessonId[" + opt.lessonId + "],caused by error:" + lessonJsonObj);
            return "error";
        }
    });

    ljRetState.code = 2;
    ljRetState.msg ="null object of uid"
    ljRetState.success = true;
    res.setHeader("Access-Control-Allow-Origin","*");
    res.json(ljRetState);

    return "";
});

var addDownload = function(opt)
{
    opt.url = apiHelper.getApiForAddDownload(opt.lessonId,opt.courseId,opt.downloadStatus, null);
    opt.method = "post";
    opt.path = "/callback/download/add";

    httpHelper.request(opt, function (error, res, body)
    {
        var retObj = JSON.parse(body);
        logHelper.debug(retObj);

        if (retObj.code == 200)
        {
            logHelper.info("Succeed to call api[" + opt.path + "]");
            return true;
        }
        else
        {
            logHelper.error("Failed to call api[" + opt.path + "],caused by error[" + retObj + "]");
            return false;
        }
    });
}

var delDownload = function(opt)
{
    opt.url = apiHelper.getApiForDelDownload(opt.lessonId, null);
    opt.method = "delete";
    opt.path = "/callback/download/delete";

    httpHelper.request(opt, function (error, res, body)
    {
        var retObj = JSON.parse(body);
        logHelper.debug(retObj);

        if (retObj.code == 200)
        {
            logHelper.info("Succeed to call api[" + opt.path + "]");
            return true;
        }
        else
        {
            logHelper.error("Failed to call api[" + opt.path + "],caused by error[" + retObj + "]");
            return false;
        }
    });
}

module.exports = router;