### codetube
    Copyright (C) 2011 payload payload@lavabit.com
    Copyright (C) 2011 dodo dodo.the.last@gmail.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>
###

{ Backbone } = require '../Backbone'
{ User } = require '../model/user'

class Users extends Backbone.Collection
    model: User

    constructor: (@client) ->
        @_byName = {}
        @_byMail = {}
        @_requested = {}
        @client.api.on 'user', (user) =>
            user.fetched = yes
            @add user
        super

    getByName: (name) ->
        name and @_byName[name.name or name]

    getByMail: (mail) ->
        mail and @_byMail[mail.email or mail]

    add: (newuser) =>
        return unless newuser?.email or newuser?.name
        if user = @getByMail(newuser) or @getByName(newuser)
            user.set newuser
        else
            super user = new User newuser
        delete @_requested[user.get('email') or user.get('name')]
        @_byName[user.get  'name'] = user
        @_byMail[user.get 'email'] = user


    fetch: (newuser = {}) =>
        return unless newuser?.email or newuser?.name
        return if @_requested[newuser.email or newuser.name]
        return if @any ((user) ->
            ((newuser.email is user.get('email') and user.has('fetched')) or
             (newuser.name  is user.get('name') and user.has('fetched'))))
        @_requested[newuser.email or newuser.name] = yes
        @client.api.emit 'user',
            email:newuser.email
            name:newuser.name


module.exports = { Users }
