var express = require('express');
var mac = require('getmac');//获取mac地址
var os = require('os');
var fs = require('fs');
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");

/**
 * 获取MAC地址
 */
router.get("/getMac", function (req, res)
{
    var mac = apiHelper.getApiForGetMac();
    ljRetState.code = 200;
    ljRetState.data = mac;
    ljRetState.success = true;
    logHelper.info(mac);
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.json(ljRetState);

    return;
});


/**
 * 下载文件
 */
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)
    {
        let obj = JSON.parse(body);
        console.info(body)
        var lessonJsonObj = JSON.parse(body);
        if (lessonJsonObj.code == 200)
        {
            /*课件-Begin*/
            //课程集合
            var courseList = lessonJsonObj.data.list;
            //课程数
            var courseListSize = courseList.length;

            //获取总共资源数
            var res_total = 0;
            for (var i = 0; i < courseListSize; i++)
            {
                var courseObj = courseList[i];
                if (courseObj.type == ljConst.RES_TYPE_IMAGE || courseObj.type == ljConst.RES_TYPE_VIDEO)
                {
                    //资源集合
                    var resourceList = courseList[i].list;

                    //资源数
                    var resourceSize = resourceList.length;
                    res_total += resourceSize
                }
                else if (courseObj.type == ljConst.RES_TYPE_AUDIO)
                {
                    if (courseObj.list.length > 0)
                    {
                        var audioObj = courseObj.list[0];

                        var image = audioObj.img;
                        var audio = audioObj.audio;

                        if (image != null && image.url != "")
                        {
                            res_total += 1;
                        }

                        if (audio != null && audio.url != "")
                        {
                            res_total += 1;
                        }
                    }
                }




            }
            logHelper.info("res_total:" + res_total);
            /*课件-End*/

            //添加下载记录
            opt.resTotal = res_total;
            opt.resSize = 0;
            addDownload(opt);
            logHelper.info("Begin to download file with lessonId【" + opt.lessonId + "】");
            //添加下载记录

            //遍历课件
            for (var i = 0; i < courseListSize; i++)
            {
                var courseObj = courseList[i];
                if (courseObj.type == ljConst.RES_TYPE_IMAGE || courseObj.type == ljConst.RES_TYPE_VIDEO)
                {
                    //资源集合
                    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, opt);
                    }
                }//处理语音
                else if (courseObj.type == ljConst.RES_TYPE_AUDIO)
                {
                    if (courseObj.list.length > 0)
                    {
                        var audioObj = courseObj.list[0];

                        var image = audioObj.img;
                        var audio = audioObj.audio;

                        //下载图片
                        if (image != null && image.url != "")
                        {
                            fileHelper.downloadFile(image.url, opt);
                        }

                        //下载语音
                        if (audio != null && audio.url != "")
                        {
                            fileHelper.downloadFile(audio.url, opt);
                        }
                    }
                }
            }
            /*课件-End*/

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

    ljRetState.code = 200;
    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 platform = os.platform();

    var fileDirNew = "";
    if (platform == "win32")
    {
        fileDirNew = fileDirStr.replace(/\*/g, '\\');
    }
    else
    {
        fileDirNew = fileDirStr.replace(/\*/g, '/');
    }

    //判断文件是否存在
    if (!fs.existsSync(fileDirNew))
    {
        ljRetState.code = 1;
        ljRetState.msg = "文件没有找到"
        ljRetState.success = false;
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.json(ljRetState);

        return false;
    }


    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")
    }
});

/**
 * 删除下载文件
 */
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;
    console.info(arg);
    //获取参数
    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);
        console.info(obj);
        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 courseObj = courseList[i];
                //处理图片删除
                if (courseObj.type == ljConst.RES_TYPE_IMAGE)
                {
                    //资源集合
                    var resourceList = courseObj.list;
                    //资源数
                    var resourceSize = resourceList.length;

                    for (var j = 0; j < resourceSize; j++)
                    {
                        var url = resourceList[j].url;
                        var delFileProp = fileHelper.getFilePropertyNoMkdir(url);
                        var delFileDir = delFileProp.folderDir + delFileProp.fileName + "_new." + delFileProp.fileType;
                        console.info("删除图片："+delFileDir);
                        //判断文件是否存在
                        if (fs.existsSync(delFileDir))
                        {
                            //删除路径
                            fs.unlinkSync(delFileDir);
                        }
                    }
                }//处理视频删除
                else if (courseObj.type == ljConst.RES_TYPE_VIDEO)
                {
                    //资源集合
                    var resourceList = courseObj.list;
                    //资源数
                    var resourceSize = resourceList.length;

                    for (var j = 0; j < resourceSize; j++)
                    {
                        var url = resourceList[j].url;
                        var delFileProp = fileHelper.getFilePropertyNoMkdir(url);
                        var delFileDir = delFileProp.folderDir + delFileProp.fileName + "_new.mp4";
                        console.info("删除视频："+delFileDir);
                        //判断文件是否存在
                        if (fs.existsSync(delFileDir))
                        {
                            //删除路径
                            fs.unlinkSync(delFileDir);
                        }
                    }
                }
                //处理语音删除
                else if (courseObj.type == ljConst.RES_TYPE_AUDIO)
                {
                    if (courseObj.list.length > 0)
                    {
                        var audioObj = courseObj.list[0];

                        var image = audioObj.img;
                        var audio = audioObj.audio;

                        //删除图片
                        if (image != null && image.url != "")
                        {
                            var delFileProp = fileHelper.getFilePropertyNoMkdir(image.url);
                            var delFileDir = delFileProp.folderDir + delFileProp.fileName + "_new." + delFileProp.fileType;

                            //判断文件是否存在
                            if (fs.existsSync(delFileDir))
                            {
                                //删除路径
                                fs.unlinkSync(delFileDir);
                            }
                        }

                        //删除语音
                        if (audio != null && audio.url != "")
                        {
                            var delFileProp = fileHelper.getFilePropertyNoMkdir(audio.url);
                            var delFileDir = delFileProp.folderDir + delFileProp.fileName + "_new.mp3";

                            //判断文件是否存在
                            if (fs.existsSync(delFileDir))
                            {
                                //删除路径
                                fs.unlinkSync(delFileDir);
                            }
                        }
                    }
                }
            }
            /*课件-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)
{
    var macAddressStr = "";
    mac.getMac(function (err, macAddress)
    {
        if (err) throw err;
        macAddressStr = macAddress; //获取mac地址
    });
    console.info("macAddressStr:" + macAddressStr);

    opt.url = apiHelper.getApiForAddDownload(opt.lessonId, opt.courseId, opt.resTotal, opt.resSize);
    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;