import VideoSerializer from 'web-client/serializers/video';
import { normalizeVideoId } from 'web-client/utilities/normalize-video-id';

export default VideoSerializer.extend({
  attrs: {
    uploadToken: { serialize: false },
    createdAt: { serialize: false },
    publishedAt: { serialize: false},
    status: { serialize: false },
    length: { serialize: false },
    notifications: { serialize: true },
    thumbnails: { serialize: false },
    channelName: { serialize: false },
    preview: { serialize: false },
    _videoUpload: { serialize: false }
  },

  serialize() {
    let json = this._super(...arguments);

    if (typeof json.thumbnail_index !== 'number') {
      delete json.thumbnail_index;
    }

    return json;
  },

  pushPayload(store, payload) {
    let modelClass = store.modelFor('manager/uploader-video');

    let normalized = this.normalizeFindRecordResponse(store, modelClass, payload);

    store.push(normalized);
  },

  normalizeCreateRecordResponse(store, primaryModelClass, payload) {
    let videoAttributes = this.extractAttributes(primaryModelClass, payload.video);
    this.applyTransforms(primaryModelClass, videoAttributes);

    let uploadAttributes = payload.upload;

    let jsonAPI = {
      data: {
        id: extractId(payload.video),
        type: 'manager/uploader-video',
        attributes: videoAttributes
      },
      included: [{
        type: 'video-upload',
        id: uploadAttributes.url,
        attributes: {
          url: uploadAttributes.url,
          token: uploadAttributes.token
        },
        relationships: {
          video: {
            data: { type: 'manager/uploader-video', id: extractId(payload.video) }
          }
        }
      }]
    };

    return jsonAPI;
  },

  normalizeQueryResponse(store, primaryModelClass, payload) {
    let data = payload.videos.map((video) => {
      let attributes = this.extractAttributes(primaryModelClass, video);
      this.applyTransforms(primaryModelClass, attributes);

      let result = {
        id: extractId(video),
        type: 'manager/uploader-video',
        attributes
      };
      return result;
    });

    return { data };
  },

  normalizeFindRecordResponse(store, primaryModelClass, video) {
    let attributes = this.extractAttributes(primaryModelClass, video);
    this.applyTransforms(primaryModelClass, attributes);

    let data = {
      id: extractId(video),
      type: 'manager/uploader-video',
      attributes
    };

    return { data };
  },

  normalizeDeleteRecordResponse() {
    // Avoid setting attributes from 200 response
    return { data: null };
  }
});

function extractId(video) {
  return normalizeVideoId(video._id);
}
