/**
 * Created with JetBrains WebStorm.
 * User: dfwang
 * Date: 14-7-14
 * Time: 下午3:46
 * To change this template use File | Settings | File Templates.
 */
define(function (require, exports) {
    var commands = require('editor/assert/js/utils/commands').commands;
    var AppContext = require('../../../../share/assert/js/appcontext').AppContext;
    var IO = require('../../../../share/assert/js/ioutil_desktop.js').IOUtil;
    var path = require('../../../../share/assert/js/path');
    var LM = require('editor/assert/js/addon/logManager').LogManager;

    fabric.Spot.prototype.showEditDialog = function (opt, finishcallback,hide) {
        var _that = this, phtml = '', tablecot = null;
        var _mjson = {items: [],cardtype: 'spot',spotImg: _that.icon,des: null};
        var _dlg = null;
        var _hotCount = 3;
        var _folder =  AppContext.joinPath(Global.CurrentSlide.c.getCurMediaPath(), _that.id);
        if(opt)
        {
            var _st = Global.CurrentSlide.c.getCurSlidePath();
            opt.src = AppContext.joinPath(_st,opt.src.replace(_st,''));
        }
        //新建添加一个rid
        if (!_that.rid) {
            var _info = {"src": AppContext.joinPath(_folder), "title": "热区", "des": "", "type": 'dir'};
            //push到Relation中避免重复创建
            _that.rid = Global.CurrentSlide.c.addRelationInfo(_info);
            this.setRelInfo(_info);
        }
        var rinfo = opt || _that.getRelInfo();
        rinfo.src = rinfo.src.replace('/meta.json','');
        //rinfo.src = AppContext.joinPath(rinfo.src,'meta.json');
        //取得json信息
        function getJson(callback) {
            IO.exists(AppContext.joinPath(rinfo.src,'meta.json')).done(function (e) {
                //操作频繁先行创建目录和meta
                if (!e) {
                    // 用户统计
                    LM.statisticsMoudleTime('4013','trigger','hots_count');

                    IO.mkdirp(_folder).done(function (e) {
                        if (e) {
                            IO.writeFile(AppContext.joinPath(rinfo.src,'meta.json'), JSON.stringify(_mjson)).done(function (e) {});
                        }
                        copyImgToFolder(AppContext.joinPath(AppContext.getDefaultImagePath(),_mjson.spotImg),function(e){})
                    })
                    if(hide) return;
                    callback && callback();
                } else {
                    IO.readFile(AppContext.joinPath(rinfo.src,'meta.json')).done(function (data, err) {
                        if (data) {
                            _mjson = JSON.parse(data);
                            if(hide) return;
                            callback && callback();
                        } else
                        {
                            commands.showPop(commands.getErrorMsg(42),2000);
                            if(hide) return;
                            setTimeout(callback,2500);
                        }
                    });
                }
            });
        };

        getJson(init);
        function init() {
            _dlg = $('<div id="modal-content" style="padding-top: 75px" class="modal fade" tabindex="-1" role="dialog"><div class="modal-dialog test_temp">' +
                    '<div class="pop_tit">' +
                        '<span class="fl">编辑热区</span>' +
                        '<div class="w_func fr">' +
                        '<a href="javascript:;" title="关闭" class="w_func_close" data-dismiss="modal"></a>' +
                        '</div>' +
                    '</div>' +
                '<div style="color: #000000">' +
                '<div class="area_border fl">文字气泡</div>' +
                '<div id="hots_text_content" style="overflow-y:auto;word-break:break-all;margin:0 5%;width: 90%;height: 150px;border: 1px solid #c0c0c0;float:left;font-size: 16px;"></div>' +
                '</div>'+
                '<div class="tst_temp_step tst_temp_hot_area">' +
                    '<ul class="graph_list">' +
                        '<li>' +
                            '<p>媒体文件</p>' +
                            '<ul class="graph_list_sun clearfix" id="hots_list_box">' +
                            '</ul>' +
                        '</li>' +
                    '</ul>' +
                    '<p class="hot_area_edit_tip" id="hots_edit_tip">您最多可以添加4个文件</p>' +
                '</div>' +
                '<div class="pop_btn_box">' +
                '<a href="javascript:;" id="hots_submit" class="pop_btn fr mrmt"><span class="pop_btn_s2">确定</span></a>' +
                '</div>' +
                '</div></div>');
            $('body').append(_dlg);
            updateDom();
            _dlg.on('hidden.bs.modal',function(e){
                Global.isEditing = false;
                _dlg.remove();
            });
            _dlg.modal({show: true,keyboard:false,backdrop:false});

            $('#hots_submit').on('click',function(e){
                var _text = $('#hots_text_content').html();
                _mjson.des =  _text? _text:null;
                IO.writeFile(AppContext.joinPath(_that.rinfo.src,'meta.json'), JSON.stringify(_mjson)).done(function(e){
                    _dlg.modal('hide');
                });
            })
            $('#hots_text_content').on('click',function(e){
//                commands.textEditorDialog(this)
                commands.renderTextEditor(this)
            })
        }
        EventBase.off('hotsClearFile');
        EventBase.addListener('hotsClearFile',function(type,target){
            var _par = $(target.parentNode);
            var _idx = Number(_par.attr('cid'))
            _mjson.items.splice(_idx,1);
            _hotCount=3;
            updateDom(true);
            $('#hots_edit_tip').text('您还可以添加'+_hotCount+'个文件');
        });

        //乱一比的视频处理
        EventBase.off('hotsSelectFile');
        EventBase.addListener('hotsSelectFile',function(type,target){
            var _url = target.value;
            if(!_url)return;
            var _e = commands.getExtName(_url)[0];
            var _ext = commands.getFileExtType(_e);
            var _type = commands.changeFileExtType(commands.getExtName(_url)[0]);
            if(_type=='video' && _e!=='.swf')
            {
                var _et = commands.changeFileExtType(_e);
                var _desurl =  commands.getExtName(commands.changeFolderToMedia(_url,_folder,true),'mp4');
                IO.getMediaThemb(AppContext.joinPath(_url)).done(function(e){
                    var _video = e.match(/Stream #.*Video:.*/g);
                    if(!_video)
                    {
                        commands.showPop(commands.getErrorMsg(2017),2000)
                        return
                    }else
                    {
                        _video = _video[0];
                    }
                    if(_video.indexOf('h264')<0 || _e !='.mp4')
                    {
                        commands.showSelectorPop(commands.getErrorMsg(2009),function(is){
                            if(is)
                            {
                                commands.hidePop();
                                IO.ffmpeg(AppContext.joinPath(_url),_desurl).done(function(e){
                                    commands.resetAppState();
                                    commands.hidePop();
                                    Global.AppState.init.value = false;
                                    if(e)
                                    {
                                        addFileToMedia(_desurl,target,false);
                                    }else{

                                        commands.showPop(commands.getErrorMsg(3011),1000);
                                    }
                                });
                                setTimeout(function(){
                                    commands.showSelectorPop(commands.getErrorMsg(2007),null,null,_that,[{
                                        label: '取消',
                                        cssClass: 'btn-primary',
                                        action: function(){
                                            cancelMediaChange.call(_that,true);
                                        }
                                    }],true)
                                },500);
                            }else
                            {
                                commands.hidePop();
                            }

                        },null,this);
                    }else
                    {
                        addFileToMedia(_url,target,true);
                    }
                });
                target.value = null;
                return;
            }else
            {
                addFileToMedia(_url,target,true);
            }
            function cancelMediaChange(_is){
                commands.hidePop();
                IO.shellexecute("taskkill /F /IM ffmpeg.exe /T");
                IO.removeFile(_desurl).done(function(e){
                    commands.resetAppState();
                });
                //IO.rmdir(_res);
                //console.log(_is);
            }
            //是否需要转换资源
            //addFileToMedia(_url,target,true)

        });

        function addFileToMedia(_url,target,_iscopy){
            var _file = getFileIcon(_url);
            if(!_file) return;
            var _dom = null;
            var _par = $(target.parentNode);
            function copy(_tosrc){
                _dom = $('<img src="'+(_file.type == 'image' ? _tosrc:_file.url)+'" >');
                if(!_tosrc)
                {
                    commands.showPop(commands.getErrorMsg(2006),2000);
                }else
                {
                    _par.find('a')[0].className = 'graph_list_close';
                    _par.find('input').css('display','none');
                    var _cid = _par.attr('cid') || 0;
                    _par.append(_dom);
                    _mjson.items[_cid] = {src: _tosrc.replace(_folder,''),type: _file.type};
                    _hotCount--;
                    $('#hots_edit_tip').text('您还可以添加'+_hotCount+'个文件');
                    if(_hotCount>0){
                        addList();
                    }
                }
            }
            if(_iscopy)
            {
                commands.showPop(commands.getErrorMsg(2002));
                copyImgToFolder(_url,function(_tosrc){
                    commands.hidePop();
                    copy(_tosrc)
                },true)
            }else
            {
                copy(_url);
            }
        }

        /**
         * 取得相应文件的图标
         * @param url
         */
        function getFileIcon(url){
            var _type = commands.changeFileExtType(commands.getExtName(url)[0]);
             if(!_type)
             {
                commands.showPop(commands.getErrorMsg(3001),1000);
                return null;
             }

            var _url = null;//AppContext.joinPath(AppContext.getDefaultImagePath(),'graph_list_img.png');
            switch (_type)
            {
                case "image":
                    _url = url;
                    break
                case "video":
                case "audio":
                    _url = AppContext.joinPath(AppContext.getDefaultImagePath(),'spot_media_icon.jpg');
                    break
            }
            return {url:_url,type:_type};
        }

        /**
         * 更新dom
         */
        function updateDom(_update){

           if(_mjson.des && !_update)
           {
               //$('#hots_text_ctrl')[0].checked = true;
               $('#hots_text_content').html(_mjson.des);
               //_ischeck = 1
               //_hotCount--;
           }
           if(_update) $('#hots_list_box').html('');
           for(var i=0;i<_mjson.items.length;i++)
           {
               var _file = getFileIcon(AppContext.joinPath(_folder,_mjson.items[i].src));
               var _li = '<li class="" cid="'+i+'"><a onclick="EventBase.fireEvent(\'hotsClearFile\',this)" href="javascript:void(0);" class="graph_list_close"  style="display: block"></a>' +
                   '<input accept=".rmvb,.mp4,.avi,.wmv,.asf,.mpeg,.3gp,.flv,.mpg,.swf,.mp3,.wav,.jpg,.jpeg,.bmp,.png,.webm" onchange="EventBase.fireEvent(\'hotsSelectFile\',this)" id="openPackage" title="点击添加文件" type="file"class="btn btn-primary"style="top: 0;position: absolute;opacity: 0;width: 81px;height: 67px;left: 0;display: none">' +
                   '<img src="'+_file.url+'" </li>';
               $('#hots_list_box').append(_li);
               _hotCount--;
           }
            addList();
        }
        function addList(){
            if(_hotCount>0)
            {
                var _li = '<li class="graph_list_add" cid="'+(3-_hotCount)+'">' +
                    '<a onclick="EventBase.fireEvent(\'hotsClearFile\',this)" href="javascript:void(0);" class="graph_list_add"></a>' +
                    '<input accept=".rmvb,.mp4,.avi,.wmv,.asf,.mpeg,.3gp,.wav,.flv,.mpg,.swf,.mp3,.jpg,.jpeg,.bmp,.png,.webm" onchange="EventBase.fireEvent(\'hotsSelectFile\',this)" id="openPackage" title="点击添加文件" type="file" class="btn btn-primary" style="top: 0;position: absolute;opacity: 0;width: 81px;height: 67px;left: 0;display: block">' +
                    '</li>' ;
                $('#hots_list_box').append(_li);
            }
            $('#hots_edit_tip').text('您还可以添加'+(_hotCount || 0)+'个文件');
        }
        //copy文件
        function copyImgToFolder(_src,_callback,media)
        {
            _src = encodeURI(AppContext.joinPath(_src));
            _src = decodeURI(_src).replace('file:///','');
            var _t = _that.rinfo.src;//.substr(0,_that.rinfo.src.lastIndexOf('/'));
            var _tosrc = AppContext.joinPath(_t,_src.substr(_src.lastIndexOf('/'),_src.length));
            if(media)
            {
                _tosrc = commands.changeFolderToMedia(_src,_t,true);
            }
            IO.copyFile(_src,_tosrc).done(function(bol){
                if(bol)
                {
                    _callback(_tosrc);
                } else
                {
                    _callback(false);
                }
            })
        }
        finishcallback && (this.callback = finishcallback);



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