/**
 * Created by feiqian on 2014/7/16.
 */
define(function (require, exports, module) {

    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 appContext = require('../../../../../share/assert/js/appcontext').AppContext;
    var LM = require('editor/assert/js/addon/logManager').LogManager;

    require("./jsonUtil.js");

    fabric.Exercise.prototype.showEditDialog = function (opt) {
        var _self = this;
        var isUpdate = false;
        if (opt) {
            isUpdate = true;
            this.id = opt.src.substr(opt.src.lastIndexOf("/") + 1);
        }

        require.async("./exerciseMgr.js", function (ExerciseMgr) {
            var exerciseMgr = new ExerciseMgr();
            var defer = $.Deferred();
            if (opt) {
                isUpdate = true;
                var metaJson;
                if (opt.src.indexOf(Global.CurrentSlide.c.getCurSlidePath()) == -1) {
                    metaJson = Path.join(Global.CurrentSlide.c.getCurSlidePath(), opt.src, 'meta.json');
                }
                else {
                    metaJson = Path.join(opt.src, 'meta.json');
                }
                IO.readFile(metaJson).done(function (content) {
                    var exerciseInfo = JSON.parse(content);
                    console.log(content);
                    var s = Global.CurrentSlide.c;
                    var wdir = Path.join(s.getCurSlidePath(), 'media', _self.id);

                    JSON.setValueByAttrName(exerciseInfo, "options,type=img&value", true, function (ret) {
                        ret["value"] = Path.join(wdir, ret["value"]);
                    });

                    JSON.setValueByAttrName(exerciseInfo, "items,thumbNail", true, function (ret) {
                        ret["thumbNail"] = Path.join(wdir, ret["thumbNail"]);
                    });

                    exerciseMgr.init(exerciseInfo.items,false,isUpdate).done(function () {
                        defer.resolve();
                    });
                });
            }
            else defer.resolve();

            defer.done(function () {
                _self._exerciseMgr = exerciseMgr;
                _self._exerciseMgr.once('save', function (exerciseInfo, thumbData) {
                    _self.saveToFile(exerciseInfo, thumbData);
                });
                exerciseMgr.showPanel(null,isUpdate);
            });
        });
    };


    fabric.Exercise.prototype.saveToFile = function (exerciseInfo, thumbData) {

        var self = this;

        var s = Global.CurrentSlide.c;
        if (!exerciseInfo)
            return;
        //是否是重新编辑
        var isUpdate = false;
        if (!self.id) {
            self.id = s.NewWId(self.type);
            Global.isVariety = true;
        } else {
            isUpdate = true;
            Global.isVariety = true;
        }
        var wdir = Path.join(s.getCurSlidePath(), 'media', self.id);
        //console.log(wdir);
        IO.mkdir(wdir).done(function () {

            //把绝对路径替换成只留图片名称
            var newExerciseImgSrcArr = [];
            JSON.setValueByAttrName(exerciseInfo, "options,type=img&value", true, function (ret) {
                var src = ret["value"];
                if (src) {
                    var newSrc = commands.randomString(5) + src.substring(src.lastIndexOf("."));
                    var desImgPath = Path.join(wdir, newSrc);
                    IO.copyFileSync(src, desImgPath);
                    ret["value"] = newSrc;
                    newExerciseImgSrcArr.push(newSrc);
                }
            });

            JSON.setValueByAttrName(exerciseInfo, "items,thumbNail", true, function (ret) {
                var src = ret["thumbNail"];
                if (src) {
                    var newSrc = commands.randomString(5) + src.substring(src.lastIndexOf("."));
                    var desImgPath = Path.join(wdir, newSrc);
                    IO.copyFileSync(src, desImgPath);
                    ret["thumbNail"] = newSrc;
                    newExerciseImgSrcArr.push(newSrc);
                }
            });

            var fs = window.require("fs");
            fs.readdir(wdir, function (err, fileNameArray) {
                if (err) {
                    console.error(err);
                }
                //删掉不在测试图片数组内的本地图片
                for (var i = 0; i < fileNameArray.length; i++) {
                    var indexFlag = $.inArray(fileNameArray[i], newExerciseImgSrcArr);
                    if (indexFlag === -1 && fileNameArray[i] !== 'meta.json') {
                        fs.unlink(Path.join(wdir, fileNameArray[i]));
                    }
                }

                var metaPath = Path.join(wdir, 'meta.json');
                IO.writeFile(metaPath, JSON.stringify(exerciseInfo)).done(function(result){
                    if(result){
                        //将base64转为图片
                        var thumbImgPath = Path.join(wdir, "thumbnail.png");

                        IO.writeIMG(thumbImgPath, thumbData).done(function () {
                            var rel = self.getRelInfo();
                            if (!isUpdate) {
                                rel = {"id": s.NewRId(), "src": Path.join('media', self.id), "title": "", "des": "", "type": "dir"};
                                s.addRelationInfo(rel);

                                self.rid = rel.id;
                                self.setRelInfo(rel);
                            }
                            self.setSrc(thumbImgPath + "?" + commands.randomString(5), function (width, height) {
                                if(self.width === 598){
                                    self.width = 700;
                                }
                                if(self.height === 478){
                                    self.height = 585;
                                }

                                if (!isUpdate) {
                                    var mainSize = s.getCanvasSize();
                                    self.width = 700;
                                    self.height = 585;
                                    self.scaleX = 1.1;
                                    self.scaleY = 1.1;
                                    self.left = (mainSize[0] - self.width * self.scaleX) * 0.5;
                                    self.top = (mainSize[1] - self.height * self.scaleY) * 0.5;
                                    s.add(self);
                                }

                                s.renderAll();

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

                                setTimeout(function () {
                                    commands.showThumbImg(Global.CurrentSlide.c._canvas);
                                }, 50);

                            });
                        });
                    }else{
                        commands.showPop("测验卡片保存失败，请重试。");
                    }
                });
            });
        });

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