import StoreModel from 'web-client/models/store';
import VideoManagerVideo from 'web-client/models/video-manager-video';
import { camelize } from 'ember-string';
import injectService from 'ember-service/inject';

export const EXPIRATION_MS = 60000;

let VideoManagerProperties = StoreModel.defineModel({
  api: injectService(),

  expiration: EXPIRATION_MS,

  relationships: {
    pastBroadcasts() {
      return VideoManagerVideo.find('pastBroadcasts', {
        channel: this.get('id')
      });
    },
    expiringPastBroadcasts() {
      return VideoManagerVideo.find('pastBroadcasts', {
        channel: this.get('id'),
        delete_at: 'expiring'
      });
    },
    highlights() {
      return VideoManagerVideo.find('highlights', {
        channel: this.get('id')
      });
    }
  },

  request() {
    return this.get('api').request('get', `/api/channels/${this.get('id')}/video_manager`);
  },

  afterSuccess(response) {
    if (!response) {
      return;
    }

    let properties = withNormalizedKeys(response);
    properties.id = this.get('id');

    VideoManagerProperties.create(properties);
  }
});

export default VideoManagerProperties;

// Add camelCased keys to but also keep around the snake_case keys for
// backwards compatibility.
function withNormalizedKeys(obj) {
  let result = {};

  Object.keys(obj).forEach((key) => {
    result[camelize(key)] = result[key] = obj[key];
  });

  return result;
}
