import got from 'got';
import getArtistTitle, { fallBackToArtist } from 'get-artist-title';

function normalizeMedia(media) {
  const [artist, title] = getArtistTitle(media.title, [
    'base',
    fallBackToArtist(media.soundtrack_artist || media['owner.username'])
  ]);

  return {
    sourceID: media.id,
    artist, title,
    duration: media.duration,
    thumbnail: media.thumbnail_360_url,
    restricted: []
  };
}

const defaultOptions = {
  api: 'https://api.dailymotion.com/',
  fields: [
    'id',
    'title',
    'owner.username',
    'allow_embed',
    'duration',
    'explicit',
    'soundtrack_artist',
    'thumbnail_360_url'
  ]
};

export default function dailymotionSource(uw, userOptions = {}) {
  const opts = {
    ...defaultOptions,
    ...userOptions
  };

  async function get(sourceIDs) {
    const { body } = await got(`${opts.api}videos`, {
      json: true,
      query: {
        limit: sourceIDs.length,
        ids: sourceIDs.join(','),
        fields: opts.fields.join(',')
      }
    });

    const videos = {};
    for (const video of body.list) {
      videos[video.id] = normalizeMedia(video);
    }

    return sourceIDs.map(id => videos[id]);
  }

  async function search(query, page = {}) {
    const { body } = await got(`${opts.api}videos`, {
      json: true,
      query: {
        search: query,
        limit: 50,
        fields: opts.fields.join(',')
      }
    });
    return body.list.map(normalizeMedia);
  }

  return {
    get: get, // eslint-disable-line object-shorthand
    search
  };
}

@@ -418,16 +418,170 @@
   %7D;%0A%7D%0A%0A
+export function getVideoId(url) %7B%0A  const match = /%5C/video%5C/(%5Bkx%5D%5Ba-zA-Z0-9%5D+)($%7C_)/.exec(url);%0A  if (match) %7B%0A    return match%5B1%5D;%0A  %7D%0A  return null;%0A%7D%0A%0A
 const de
@@ -932,16 +932,243 @@
 s%0A  %7D;%0A%0A
+  async function getOne(sourceID) %7B%0A    const %7B body %7D = await got(%60$%7Bopts.api%7Dvideo/$%7BsourceID%7D%60, %7B%0A      json: true,%0A      query: %7B%0A        fields: opts.fields.join(',')%0A      %7D%0A    %7D);%0A%0A    return normalizeMedia(body);%0A  %7D%0A%0A
   async 
@@ -1558,32 +1558,32 @@
 deos%5Bid%5D);%0A  %7D%0A%0A
-
   async function
@@ -1606,24 +1606,111 @@
 age = %7B%7D) %7B%0A
+    const id = getVideoId(query);%0A    if (id) %7B%0A      return %5Bawait getOne(id)%5D;%0A    %7D%0A
     const %7B 

return single when searching for a URL