import {fetch} from './fetch';
import map from 'lodash/map';
import filter from 'lodash/filter';
import every from 'lodash/every';

export default class ChannelService {
  constructor() {
    this.channels = [];
    this.contentTypes = [];
    this.pressReleaseTypes = [];
    this.contentTypeLabels = { /* eslint-disable */ // allows for spacing like below
      'syndicated_links':       { name: 'Partner',        shortName: '' },
      'bzsyndicatefeed':        { name: 'Syndicate',      shortName: '' },
      'regfdfeed':              { name: 'Reg FD',         shortName: '' },
      'story':                  { name: 'BZ Wire',        shortName: '' },
      'accesswire_story':       { name: 'BayStreet',      shortName: '' },
      'acnewswire_story':       { name: 'ACN',            shortName: '' },
      'businesswire_story':     { name: 'BW',             shortName: '' },
      'bz_pr_thomson_reuters':  { name: 'REUT',           shortName: '' },
      'comtex_story':           { name: 'Comtex',         shortName: '' },
      'emailwire_story':        { name: 'Emailwire',      shortName: '' },
      'eteligis_story':         { name: 'eTeligis',       shortName: '' },
      'globenewswire_story':    { name: 'GLN',            shortName: '' },
      'marketwire_story':       { name: 'MW',             shortName: '' },
      'newswire_pressreleases': { name: 'PRN',            shortName: '' },
      'newswire_story':         { name: 'PRN',            shortName: '' },
      'pr_story':               { name: 'Press Releases', shortName: 'PR' },
      'prweb_story':            { name: 'PRWeb',          shortName: '' },
      'webwire_story':          { name: 'Webwire',        shortName: '' },
      'pr_bzsignals':           { name: 'BZ Signals',     shortName: '' },
      'pr_forexlive':           { name: 'ForexLive',      shortName: '' },
      'pr_secfilings':          { name: 'SEC Filings',    shortName: 'SEC' },
    }; /* eslint-enable */
  }

  connect() {
    this.loadChannels();
    this.loadContentTypes();
  }

  loadChannels() {
    fetch(process.env.SERVICES_ROOT + '/services/watchlist/bzuser/channel/', {
      headers: {
        'accept': 'application/json',
        'x-device-key': localStorage.authKey,
        'content-type': 'application/json'
      },
      method: 'get'
    })
    .then(resp => resp.json())
    .then(data => this.channels = map(data.data, (v) => ({
      id: v.channel_id,
      name: v.channel_name,
      tids: map(v.tids, 'tid')
    })));
  }

  loadContentTypes() {
    fetch('https://www.benzinga.com/ajax-cache/content-types-for-pro', {
      headers: {'accept': 'application/json'},
      method: 'get'
    })
    .then(resp => resp.json())
    .then(data => {
      // must convert .type (as it comes from the API) to .id
      map(data.types, (source) => { source.id = source.type; delete source.type; });

      // Skip press releases as we are grouping them all as one
      this.contentTypes = filter(data.types, (v) => data.pr_types.indexOf(v.id) === -1 && v.id !== 'bzsyndicatefeed');
      this.pressReleaseTypes = data.pr_types;
      this.contentTypes.push({name: 'Press Releases', type: 'pr_story', description: 'Feed of company Press Releases'});
    });
  }

  convertTidsToIds(selectedTids, allChannels) {
    if (selectedTids === undefined || allChannels === undefined) { return []; }
    const output = [];
    const tids = new Set();
    selectedTids.forEach((tid) => tids.add(tid));
    allChannels.forEach((channel) => {
      if (every(channel.tids, (tid) => tids.has(tid))) {
        output.push(channel.id);
      }
    });
    return output;
  }

  convertIdsToTids(selectedChannels, allChannels) {
    if (selectedChannels === undefined || allChannels === undefined) { return []; }
    let output = [];
    selectedChannels.forEach((selectedChannel) => {
      allChannels.forEach((channel) => {
        if (channel.id === selectedChannel) {
          channel.tids.forEach((tid) => output.push(tid));
        }
      });
    });
    output = output.sort((a, b) => a < b); // sorts ascending
    return output;
  }

  sourceIdToName(id) {
    if (this.contentTypeLabels[id]) {
      return this.contentTypeLabels[id].name || 'News';
    }
    return 'News';
  }

  storyToName(story) {
    if (story.Type === 'story') {
      return story.IsBzProPost ? 'BZ Wire' : 'Benzinga';
    }
    return this.sourceIdToName(story.Type);
  }

  sourceIdToShortName(id) {
    if (this.contentTypeLabels[id]) {
      return this.contentTypeLabels[id].shortName || this.sourceIdToName(id);
    }
    return this.sourceIdToName(id);
  }

  storyToShortName(story) {
    if (story.Type === 'story') {
      return story.IsBzProPost ? 'BZ Wire' : 'Benzinga';
    }
    return this.sourceIdToShortName(story.Type);
  }

  isPressReleaseType(type) {
    return this.pressReleaseTypes.indexOf(type) > -1;
  }

  getContentTypes() {
    return this.contentTypes;
  }

  getPressReleaseTypes() {
    return this.pressReleaseTypes;
  }

  getAllChannels() {
    return this.channels;
  }
}
