import { getClient } from './google'
import getEmail from './get_email'
import moment from 'moment'

const getEmails = async (req, params) => {

  const { profile, type } = params

  const client = await getClient(req, {
    profile,
    service: 'gmail'
  })

  const pageToken = _.get(req, 'query.$page.next')

  const email = params.email

  const label = type === 'sent' ? 'to' : 'from'

  const since = params.since || '1900-01-01'

  const filters = [
    ...email ? [`${label}:"${email}"`] : [],
    ...since ? [`after:${moment(since).format('X')}`] : []
  ]

  const result = await client.users.messages.list({
    ...type ? {
      labelIds: type === 'sent' ? ['SENT'] : ['INBOX']
    } : {},
    ...pageToken ? { pageToken } : {},
    userId: 'me',
    q: filters.length > 0 ? filters.join(' ') : null,
    maxResults: 100
  })

  const messages = result.data.messages || []

  const records = await Promise.mapSeries(messages, async entry => {
    return await getEmail(req, {
      client,
      id: entry.id
    })
  })

  records.pagination = {
    skip: pageToken ? 1 : 0,
    next: result.data.nextPageToken || null
  }

  return records

}

export default getEmails
