/**
 * Created with JetBrains WebStorm.
 * User: Cmma
 * Date: 7/11/14
 * Time: 11:36 AM
 * To change this template use File | Settings | File Templates.
 */
define(function (require, exports) {
    var Path = require('../../../../../share/assert/js/path');
    var IO = require('../../../../../share/assert/js/ioutil_desktop.js').IOUtil;
    var commands = require('editor/assert/js/utils/commands').commands;
    var pptConverter = window.require('documentconverter/AddonDocumentConverter');
    var LM = require('editor/assert/js/addon/logManager').LogManager;
    var PPTTemplate = require("./ppttemplate.js").PPTTemplate;

    var slider = null
    var imagesArr = [];
    var pptFileName = "";
    var fullDir = "";
    var pptFilePath = "";
    var id = "";
    var oldid = ""; //编译ppt失败后回退
    var isUpdate = false;
    var quit = false;   //转换过程中关闭窗口
    var instanceID = "";
    var firstid = ""; //更新操作时记录的文件夹id


    function CovertPPT2Images(taksid, callback) {
        slider = Global.CurrentSlide.c;
        fullDir = Path.join(slider.getCurSlidePath(), 'media', id);
        IO.rmdir(fullDir).done(function () {
            IO.mkdir(fullDir).done(function () {
                pptFileName = pptFilePath.substring(pptFilePath.lastIndexOf("\\") + 1);
                var appPath = process.cwd();
                var modulePath = Path.join(appPath, "node_modules", "documentconverter");
                pptConverter.document2Image(pptFilePath, fullDir, id + '_', modulePath, function (errMsg, errCode, num) {
                    if (errCode == 0 && num > 0) {
                        imagesArr.length = 0;
                        for (var i = 1; i < num + 1; i++) {
                            imagesArr.push(id + '_' + i.toString() + '.png');
                        }
                        if (oldid != "" && firstid != oldid && taksid == instanceID) {
                            IO.rmdir(Path.join(slider.getCurSlidePath(), 'media', oldid));  //清除上一次的临时文件
                        }
                    }
                    callback(taksid, errCode);
                });
            });
        });
    }

    function selectFile(callback) {
        var option = {multiple: true, accept: ".ppt, .pptx"};
        DialogUtil.openFileDialog(option).done(function (filePath) {
            pptFilePath = filePath;
            callback();
        });
    }


    function createDlg(){
        if ($('#modal-content'))    $('#modal-content').remove();

        var def = jQuery.Deferred();
        seajs.use('editor/assert/js/widget/pptcard/pptcardEditor.tpl', function (tpl) {
            var dlg = $(tpl);
            $('body').append(dlg);
            var top = (window.innerHeight - 600) / 2;
            dlg.css("paddingTop", top);
            def.resolve(dlg);
        });

        return def.promise();
    }

    fabric.PPT.prototype.showEditDialog = function (opt, finishcallback) {
        console.log("ppt edit fired!", opt);
        var _self = this;
        Global.isEditing = true;
        Global.isVariety = true;
        var dlg = createDlg().done(function (dlg) {
            isUpdate = false;
            if (opt)    isUpdate = true;

            dlg.on('hidden.bs.modal', function (e) {
                Global.isEditing = false;
            });

            PPTTemplate.init();

            quit = false;
            var clientHeight = document.body.clientHeight;
            dlg.find(".modal-content").css("margin-top", (clientHeight - 500) / 2);
            $("#btnFinish").hide();
            _self.dlg = dlg;
            dlg.modal({show: true, keyboard: false, backdrop: "static"});

            instanceID = commands.randomString(10);
            id = "";
            oldid = "";
            pptFilePath = "";
            //编辑功能
            if (isUpdate) {
                var slidePath = Global.CurrentSlide.c.getCurSlidePath();
                var pptWidgetPath;
                if (opt.src.indexOf(slidePath) == -1) {
                    pptWidgetPath = Path.join(slidePath, opt.src);
                }
                else {
                    pptWidgetPath = opt.src;
                }
                var metaJson = Path.join(pptWidgetPath, "meta.json");
                $("#btnFinish").show();
                IO.readFile(metaJson).done(function (jsonStr) {
                    var jsonObj = JSON.parse(jsonStr);
                    imagesArr = jsonObj.images;
                    jsonObj.thumbnail = Path.join(pptWidgetPath, jsonObj.images[0]);
                    pptFileName = jsonObj.file;
                    PPTTemplate.UpdateWidgetInfo(jsonObj);
                    id = opt.src.substr(opt.src.lastIndexOf("/") + 1);
                    firstid = id;
                    //id = jsonObj.rid;
                });
            }

            $("#pptImgBtn").click(function () {
                selectFile(function () {
                    slider = Global.CurrentSlide.c;
                    oldid = id;
                    id = slider.NewWId(_self.type);
                    PPTTemplate.cleanOperMsg();
                    PPTTemplate.SetBusyStatus();
                    $("#btnFinish").hide();
                    CovertPPT2Images(instanceID, function (taskid, errCode) {
                        if (quit || taskid != instanceID) {   //转换过程中关闭窗口
                            return;
                        }
                        if (errCode == 0) {
                            PPTTemplate.setThumbNailPath(Path.join(fullDir, imagesArr[0]));
                            $("#btnFinish").show();
                        }
                        else {
                            //iframe.contentWindow.pptTemplate.setOperMsg("处理文件失败");
                            if (isUpdate) {
                                $("#btnFinish").show();
                                id = oldid;
                            }

                            // 处理错误代码
                            if (errCode == 103){    //不支持的文件类型
                                commands.showPop("您的PPT编辑版本过低，请将原PPT的.ppt格式另存为.pptx格式后再导入。");
                            }
                            else if (errCode == 10){    //环境不支持
                                var popContent = "<div id='pptNetLink'>您尚未安装windows组件无法进行操作，点击<a href='#' style='color:#b94a48'><B>此处</B></a>立即下载安装。</div>";
                                commands.showPop(popContent);
                                $("#pptNetLink").find("a").click(function () {
                                    var gui = window.require('nw.gui');
                                    gui.Shell.openExternal("http://www.microsoft.com/zh-cn/download/details.aspx?id=17718");
                                });
                            }
                            else {
                                commands.showPop("文件转换失败！");
                            }
                        }
                        PPTTemplate.SetFinishedStatus();
                    });
                })
            });

            dlg.find("#btnFinish").bind('click', function () {
                if (!isUpdate && !pptFilePath)  return;

                if(!isUpdate) {  // 用户统计
                    LM.statisticsMoudleTime('4004','trigger','ppt_count');
                }

                PPTTemplate.getpptInfo(function (galleryInfo, thumbData) {
                    if (galleryInfo) {
                        _self.saveToFile(galleryInfo, thumbData);
                    }
                });
            });

            dlg.find(".test_temp_close").bind('click', function () {
                quit = true;
                dlg.modal('hide');
                setTimeout(function () {
                    dlg.remove();
                    $("body").find(".modal-backdrop.fade.in").remove();
                }, 500);
            });
        });
    };

    fabric.PPT.prototype.saveToFile = function (pptInfo, thumbData) {
        var _self = this;
        slider = Global.CurrentSlide.c;
        Global.isVariety = true;
        if (isUpdate && firstid != id) {
            IO.rmdir(Path.join(slider.getCurSlidePath(), 'media', firstid));  //清除更新时的临时文件
        }
        fullDir = Path.join(slider.getCurSlidePath(), 'media', id);
        if (pptFilePath) {
            pptFileName = commands.randomString(10) + Path.extname(pptFileName);
            var desFilePath = Path.join(fullDir, pptFileName);
            IO.copyFileSync(pptFilePath, desFilePath);
        }
        pptInfo.file = pptFileName;
        pptInfo.thumbnail = "thumbnail.png";
        pptInfo.images = imagesArr;
        var metaPath = Path.join(fullDir, 'meta.json');

        IO.writeFile(metaPath, JSON.stringify(pptInfo));
        var thumbImgPath = Path.join(fullDir, "thumbnail.png");
        IO.writeIMG(thumbImgPath, thumbData).done(function () {
            var rel = _self.getRelInfo();
            if (!isUpdate) {
                rel = {"id": slider.NewRId(), "src": Path.join("media", id), "title": "", "des": "", "type": "dir"};
                slider.addRelationInfo(rel);
                _self.rid = rel.id;
                _self.setRelInfo(rel);
            }
            else {
                rel.src = Path.join("media", id);
            }
            _self.setSrc(thumbImgPath + "?" + commands.randomString(10), function () {
                if (!isUpdate) {
                    _self.scaleX = 1.5;
                    _self.scaleY = 1.5;

                    var mainSize = slider.getCanvasSize();
                    _self.left = (mainSize[0] - _self.width * _self.scaleX) * 0.5;
                    _self.top = (mainSize[1] - _self.height * _self.scaleY) * 0.5;
                    slider.add(_self);
                }
                slider.renderAll();
                setTimeout(function () {
                    commands.showThumbImg(Global.CurrentSlide.c._canvas);
                });
                //callback();
                _self.dlg.modal('hide');
                setTimeout(function () {
                    _self.dlg.remove();
                    $("body").find(".modal-backdrop.fade.in").remove();
                }, 500);
            });
        });
    }

    function getRightPostion(canvasSize, eleSize) {
        var x = (canvasSize[0] - eleSize[0]) / 2;
        var y = (canvasSize[1] - eleSize[1]) / 2;
        return [x, y];
    }

    fabric.PPT.prototype.hidePropertyButton = function () {
        commands.usePropertyCtrlArea(null);
    };
    fabric.PPT.prototype.showPropertyButton = function () {
        commands.usePropertyCtrlArea('object');
    };

})