import { partial } from 'ap'
import wrapUser from '../data/user'

export default function friendsPlugin () {
  return (mp) => {
    // REST Friend API
    const getFriends = () =>
      mp.get('friends').map(wrapUser)
    const befriend = (uid) =>
      mp.post('friends', { id: uid })
    const unfriend = (uid) =>
      mp.del(`friends/${uid}`)
    const getFriendRequests = partial(mp.get, 'friends/invites')
    const rejectFriendRequest = (uid) =>
      mp.put('friends/ignore', { id: uid })

    // Public API
    Object.assign(mp, {
      getFriends,
      befriend,
      unfriend,
      getFriendRequests,
      rejectFriendRequest
    })
  }
}

@@ -29,16 +29,63 @@
 %0Aimport 
+%7B unescape %7D from 'plug-message-split'%0Aimport _
 wrapUser
@@ -168,16 +168,614 @@
 p) =%3E %7B%0A
+    const wrapUser = partial(_wrapUser, mp)%0A%0A    function onFriendRequest (name) %7B%0A      getFriendRequests().each((request) =%3E %7B%0A        if (unescape(request.username) === unescape(name)) %7B%0A          mp.emit('friendRequest', wrapUser(request))%0A        %7D%0A      %7D)%0A    %7D%0A%0A    function onFriendAccept (name) %7B%0A      getFriends().each((friend) =%3E %7B%0A        if (friend.username === unescape(name)) %7B%0A          mp.emit('friendAccept', friend)%0A        %7D%0A      %7D)%0A    %7D%0A%0A    mp.on('connected', () =%3E %7B%0A      mp.ws.on('friendRequest', onFriendRequest)%0A      mp.ws.on('friendAccept', onFriendAccept)%0A    %7D)%0A%0A
     // R

Implement friendRequest/friendAccept events.