import JSONSerializer from 'ember-data/serializers/json';
import { JTV_USER_PICTURES_404_USER_70X70_URL } from 'web-client/utilities/urls/static-cdn';
import { getRecommendedReason } from 'web-client/utilities/friends-list/reasons';
import injectService from 'ember-service/inject';

export default JSONSerializer.extend({
  isNewSerializerAPI: true,
  session: injectService(),

  _normalizeChannels(channels) {
    let data = channels.map(channel => {
      return {
        id: channel._id,
        type: 'friends-list-user',
        attributes: {
          login: channel.name,
          displayName: channel.display_name,
          avatar: channel.logo || JTV_USER_PICTURES_404_USER_70X70_URL
        }
      };
    });
    return { data };
  },

  _normalizeFriend(friend) {
    let friendId = friend.user_id.toString();
    let selfId = this.get('session.userData.id').toString();
    return {
      id: friendId,
      type: 'friends-list-user',
      attributes: {
        activities: friend.activities || [],
        isFriend: friendId !== selfId,
        availability: friend.availability,
        createdAt: friend.timestamp
      }
    };
  },

  _normalizeFriends(friends) {
    let data = friends.map(this._normalizeFriend.bind(this));
    return { data };
  },

  _normalizeRecommendedUsers(users) {
    return {
      data: users.recommendations.map(userObject => {
        return this._normalizeUser(userObject.user, userObject.reason);
      }),
      meta: {
        source: users.source
      }
    };
  },

  _normalizeUser(user, recommendedReason) {
    let _user = {
      id: (user._id || user.id).toString(),
      type: 'friends-list-user',
      attributes: {
        avatar: user.logo || JTV_USER_PICTURES_404_USER_70X70_URL,
        displayName: user.display_name,
        login: user.login || user.name || user.display_name.toLowerCase()
      }
    };

    if (user.created_at) {
      _user.attributes.createdAt = user.created_at;
    }

    if (recommendedReason) {
        _user.attributes.recommendedReason = getRecommendedReason(recommendedReason);
    }

    return _user;
  },

  _normalizeUsers(users) {
    return {
      data: users.map(user => {
        return this._normalizeUser(user);
      })
    };
  },

  normalizeQueryResponse(store, klass, payload) {
    if (payload.channels) {
      return this._normalizeChannels(payload.channels);
    } else if (payload.data) {
      return this._normalizeFriends(payload.data);
    } else if (payload.users) {
      return this._normalizeUsers(payload.users);
    } else if (payload.recommendations) {
      return this._normalizeRecommendedUsers(payload);
    }
  },

  normalizeQueryRecordResponse(store, klass, payload) {
    // queryRecord unrecommend is a delete request that returns an empty body
    if (payload === undefined) {
      return {data: null};
    }

    if (payload.action === 'unfriend') {
      return {
        data: {
          id: payload.params.id.toString(),
          type: 'friends-list-user',
          attributes: { isFriend: false }
        }
      };
    }

    let response,
        id = payload.user._id.toString(),
        user = {
          id,
          type: 'friends-list-user',
          attributes: {
            isFriend: payload.status === 'friends',
            isRequested: payload.status === 'sent_request',
            isRequestedBy: payload.status === 'requested_by'
          }
        };

    response = { data: user };

    if (user.attributes.isRequestedBy || user.attributes.isRequested) {
      response.included = [{
        id,
        type: 'friends-list-request',
        attributes: {
          friendId: id,
          friendLogin: payload.user.name,
          isPending: user.attributes.isRequestedBy
        },

        relationships: {
          user: {
            data: {
              type: 'friends-list-user',
              id
            }
          }
        }
      }];
    }

    return response;
  },

  pushPayload(store, payload) {
    if (payload.type !== 'presence') {
      return;
    }
    let data = this._normalizeFriend(payload.data);
    store.push({ data });
  }

});
