/**
 * Ext.ux.ToolCopyButton - Tool Copy Button
 * Version 1.0
 * James Dempster letssurf@gmail.com
 * http://code.jdempster.com/
 */

/*global Ext,ZeroClipboard*/
Ext.namespace('Ext.ux');

/**
 * @class Ext.ux.ToolCopyButton
 * @extends Ext.Button
 * @constructor
 * @param {Object} config
 */
Ext.ux.ToolCopyButton = Ext.extend(Ext.Button, {

    init: function(panel) {
        this.panel = panel;
        this.clip = new ZeroClipboard.Client();
        this.panel.on('render', this.onRender, this);
        
        Ext.applyIf(this, {
            toolId: 'gear'
        });

        if (!Ext.isArray(panel.tools)) {
            if (panel.tools) {
                panel.tools = [panel.tools];
            } else {
                panel.tools = [];
            }
        }
        panel.tools.push({
            id: this.toolId,
            on: {
                scope: this,
                mouseover: this.onMouseOver
            }
        });
    },

    // private
    onRender: function() {
        this.tool = this.panel.getTool(this.toolId);
        this.overCls = 'x-tool-'+this.toolId+'-over';
        this.tool.destroy = this.onDestroy.createDelegate(this);

        this.clip.setCSSEffects(false);
        this.clip.glue(this.tool.dom);
        Ext.fly(this.clip.div).setStyle('z-index', 99999);
        this.clip.hide();
        this.clip.addEventListener('mouseOver', this.clipMouseOver.createDelegate(this));
        this.clip.addEventListener('mouseOut', this.clipMouseOut.createDelegate(this));
        this.clip.addEventListener('mouseDown', this.clipMouseDown.createDelegate(this));
        this.clip.addEventListener('mouseUp', this.clipMouseUp.createDelegate(this));
    },

    // private
    onDestroy: function() {
        this.clip.destroy();
        this.tool.removeAllListeners();
        this.tool.remove();
    },

    // private
    onMouseOver: function() {
        this.clip.show();
    },

    // private
    clipMouseOver: function() {
        this.tool.addClass(this.overCls);
    },

    // private
    clipMouseOut: function() {
        this.clip.hide();
        this.tool.removeClass(this.overCls);
    },

    // private
    clipMouseDown: function() {
        this.clip.setText(this.getValue());
    },

    // private
    clipMouseUp: function() {
        this.tool.removeClass(this.overCls);
    },

    /**
     * Sets the value that should be used when the button is pressed
     * @param {String} value The value to set
     */
    setValue: function(value) {
        this.value = String(value);
    },

    /**
     * Get the value that will be used when the user clicks the button
     * @return {String} value The value used to copy to the clipboard
     */
    getValue: function() {
        return this.value;
    }
});