'use strict';

oml.ui.peersButton = function() {

    var requests = 0,

        that = Ox.Element({
                tooltip: Ox._('No peering requests')
            })
            .css({
                marginRight: '6px'
            }),

        $count;

    Ox.Button({
            style: 'symbol',
            title: 'user',
            type: 'image'
        })
        .css({
            float: 'left',
            borderRadius: 0
        })
        .bindEvent({
            click: function() {
                oml.UI.set({page: 'peers'});
            }
        })
        .appendTo(that);

    $count = Ox.Element()
        .addClass('OxLight')
        .css({
            float: 'left',
            marginTop: '2px',
            fontSize: '9px',
            lineHeight: '12px'
        })
        .html('0')
        .bindEvent({
            anyclick: function() {
                oml.UI.set({page: 'peers'});
            }
        })
        .appendTo(that);

    oml.bindEvent({
        peering: update
    });
    update();

    function update() {
        // wait for clearCache in folder.js
        setTimeout(function() {
            oml.api.getUsers(function(result) {
                requests = result.data.users.filter(function(user) {
                    return user.pending == 'received';
                }).length;
                $count.html(requests);
                that.options({
                    tooltip: requests
                        ? Ox.formatCount(requests, '{0} peering request')
                        : Ox._('No peering requests')
                });
            });
        });
    }

    return that;

};