/**
 * QQ 旋风 Chrome 扩展
 * @class XF_BK
 * @author wangezhu <wangezhu@tencent.com>
 * @date 2014-03-11
 */

function XF_BK() {
    this.chrome = chrome || {};
    this.blackList = [];
    this.hostName = 'com.qq.xf.download';
    this.menu = {
        single: 'menu_title_single',
        all: 'menu_title_all',
        topSpeed: 'menu_title_topspeed',
        offline: 'menu_title_offline'
    };
}

XF_BK.isExtEnabled = true;
XF_BK.isBhoEnabled = false;
XF_BK.portNative = null;
// XF_BK.strFlag = '';

/**
 * 获取扩展状态
 */
XF_BK.prototype.getExtensionStatus = function() {
    return XF_BK.isExtEnabled;
}

/**
 * 设置扩展状态
 */
XF_BK.prototype.setExtensionStatus = function(status) {
    return XF_BK.isExtEnabled = !!status;
}

/**
 * 修改扩展状态
 */
XF_BK.prototype.changeExtensionStatus = function(extEnabledStatus) {
    var _this = this;
    _this.setExtensionStatus(extEnabledStatus);
    _this.updateBrowserActionIcon(extEnabledStatus);
    _this.updateContextMenu(extEnabledStatus);
    
    _this.chrome.tabs.getSelected(null, function(tab) {
        _this.chrome.tabs.sendMessage(tab.id,{
            status: extEnabledStatus
        }, function(response) {});
    });
    return;
}

/**
 * 更新扩展图标
 */
XF_BK.prototype.updateBrowserActionIcon = function(status) {
    this.chrome.browserAction.setIcon({
        path: status ? 'icon19.png' : 'icon19_disabled.png'
    });
    
    return;
}

/**
 * 更新菜单
 */
XF_BK.prototype.updateContextMenu = function(status) {
    this.chrome.contextMenus.update(this.menu.single, {enabled: status});
    this.chrome.contextMenus.update(this.menu.all, {enabled: status});
    this.chrome.contextMenus.update(this.menu.topSpeed, {enabled: status});
    this.chrome.contextMenus.update(this.menu.offline, {enabled: status});
    
    return;
}

/**
 * 创建菜单
 */
XF_BK.prototype.createContextMenu = function() {
    var _this = this,
        contextsSingle = ['link', 'image', 'video', 'audio'],
        contextsAll = ['all'];
        
    _this.chrome.contextMenus.removeAll();
    
    _this.chrome.contextMenus.create({
        id: _this.menu.single,
        title: _this.chrome.i18n.getMessage(_this.menu.single),
        contexts: contextsSingle,
        onclick: function(info, tab) {
            _this.onDownloadSingle(info, tab);
        }
    });
    
    _this.chrome.contextMenus.create({
        id: _this.menu.all,
        title: _this.chrome.i18n.getMessage(_this.menu.all),
        contexts: contextsAll,
        onclick: function(info, tab) {
            _this.onDownloadAll(info, tab);
        }
    });
    
    _this.chrome.contextMenus.create({
        id: _this.menu.topSpeed,
        title: _this.chrome.i18n.getMessage(_this.menu.topSpeed),
        contexts: contextsSingle,
        onclick: function(info, tab) {
            _this.onDownloadTopSpeed(info, tab);
        }
    });
    
    _this.chrome.contextMenus.create({
        id: _this.menu.offline,
        title: _this.chrome.i18n.getMessage(_this.menu.offline),
        contexts: contextsSingle,
        onclick: function(info, tab) {
            _this.OnQQDownloadOFFLine(info, tab);
        }
    });
    
    return;
}

XF_BK.prototype.disableContextMenu = function() {
    //console.log('disableContextMenu');
}

/**
 * 单个下载
 */
XF_BK.prototype.onDownloadSingle = function(info, tab) {
    var msg = {
            cmd: 'download_single',
            url: info.linkUrl || info.srcUrl || ''
        },
        port = this.chrome.tabs.connect(tab.id, {
            name: 'download_single'
        });
    port.postMessage(msg);
    port.onMessage.addListener(function(msg) {});
    
    return;
}

/**
 * 全部下载
 */
XF_BK.prototype.onDownloadAll = function(info, tab) {
    var msg = {
            cmd: 'download_all',
            url: 'download_all'
        },
        port = this.chrome.tabs.connect(tab.id, {
            name: 'download_all'
        });
    port.postMessage(msg);
    port.onMessage.addListener(function(msg) {});

    return;
}

/**
 * 极速下载
 */
XF_BK.prototype.onDownloadTopSpeed = function(info, tab) {
    var msg = {
            cmd: 'download_topspeed',
            url: info.linkUrl || info.srcUrl || ''
        },
        port = this.chrome.tabs.connect(tab.id, {
            name: 'download_topspeed'
        });
    port.postMessage(msg);
    port.onMessage.addListener(function(msg) {});
   
    return;
}

/**
 * 离线下载
 */
XF_BK.prototype.OnQQDownloadOFFLine = function(info, tab) {
    var msg = {
            cmd: 'download_offline',
            url: info.linkUrl || info.srcUrl || ''
        },
        port = this.chrome.tabs.connect(tab.id, {
            name: 'download_offline'
        });
    port.postMessage(msg);
    port.onMessage.addListener(function(msg) {});
    
    return;
}

/**
 * 监听
 */
XF_BK.prototype.onRequest = function() {
    var _this = this;
    _this.chrome.extension.onRequest.addListener(
        function(request, sender, sendResponse) {
            if (request.cmd === 'start_task') {
                _this.startTask(request.json);
            }
        }
    );
    
    return;
}

/**
 * 建立连接
 */
XF_BK.prototype.connectNative = function() {
    XF_BK.portNative = this.chrome.runtime.connectNative(this.hostName);
    XF_BK.portNative.onMessage.addListener(this.onNativeMessage);
    XF_BK.portNative.onDisconnect.addListener(this.onDisconnected);

    return;
}

/**
 * 触发本地消息
 */
XF_BK.prototype.onNativeMessage = function(message) {
    // XF_BK.strFlag = JSON.stringify(message);
    XF_BK.isBhoEnabled = true;
    
    return;
}

/**
 * 触发断开连接
 */
XF_BK.prototype.onDisconnected = function() {
    //console.log('XF_BK.isBhoEnabled:'+XF_BK.isBhoEnabled);
    XF_BK.portNative = null;
    
    // 如果旋风被卸载，更新右键菜单
    if (!XF_BK.isBhoEnabled) {

        
        var menu = {
                single: 'menu_title_single',
                all: 'menu_title_all',
                topSpeed: 'menu_title_topspeed',
                offline: 'menu_title_offline'
            },
            contextsSingle = ['link', 'image', 'video', 'audio'],
            contextsAll = ['all'];
            
        chrome.contextMenus.removeAll();
    
        chrome.contextMenus.create({
            id: menu.single,
            title: '使用旋风下载（未安装）',
            contexts: contextsSingle,
            onclick: function(info, tab) {
                window.open('http://xf.qq.com');
            }
        });
        
        chrome.contextMenus.create({
            id: menu.all,
            title: '使用旋风下载全部链接（未安装）',
            contexts: contextsAll,
            onclick: function(info, tab) {
                window.open('http://xf.qq.com');
            }
        });
        
        chrome.contextMenus.create({
            id: menu.topSpeed,
            title: '使用旋风极速下载（未安装）',
            contexts: contextsSingle,
            onclick: function(info, tab) {
                window.open('http://xf.qq.com');
            }
        });
        
        chrome.contextMenus.create({
            id: menu.offline,
            title: '保存到旋风空间（未安装）',
            contexts: contextsSingle,
            onclick: function(info, tab) {
                window.open('http://xf.qq.com');
            }
        });
    }
    return;
}

/**
 * 发送消息(长连接)
 */
XF_BK.prototype.sendNativeMessage = function(message) {
    var _this = this;
    if (XF_BK.isBhoEnabled) {
        XF_BK.portNative = _this.chrome.runtime.connectNative(_this.hostName);
        XF_BK.portNative.postMessage(message);
    } else {
        chrome.tabs.getSelected(null, function(tab) {
            chrome.tabs.sendMessage(tab.id,{
                status: false
            }, function(response) {});
        });
    }
    
    return;
}

/**
 * 开始下载
 */
XF_BK.prototype.startTask = function(jsonStr) {
    this.sendNativeMessage(jsonStr);
    
    return;
}

/**
 * 初始化
 */
XF_BK.prototype.init = function() {
    this.createContextMenu();
    this.onRequest();
    this.connectNative();
    
    return;
}

/**
 * 实例化
 */
new XF_BK().init();