import { createTrigger, fetchCollection } from 'redux-cozy-client'

export const DOCTYPE = 'io.cozy.triggers'
const triggersCollectionKey = 'triggers'

export const fetchTriggers = () =>
  fetchCollection(triggersCollectionKey, DOCTYPE)
export const createKonnectorTrigger = (
  konnector,
  account,
  folder,
  options = {}
) =>
  createTrigger(buildKonnectorTrigger(konnector, account, folder, options), {
    updateCollections: [triggersCollectionKey]
  })

export function buildKonnectorTrigger(
  konnector,
  account,
  folder,
  options = {}
) {
  const { day, hours, minutes } = options

  let workerArguments = {
    konnector: konnector.slug || konnector.attributes.slug,
    account: account._id
  }

  if (folder) {
    workerArguments['folder_to_save'] = folder._id
  }

  return {
    _type: DOCTYPE,
    attributes: {
      type: '@cron',
      arguments: `0 ${minutes || 0} ${hours || 0} * * ${day || '*'}`,
      worker: 'konnector',
      workerArguments: workerArguments
    }
  }
}

@@ -4,66 +4,92 @@
 ort 
-%7B createTrigger, fetchCollection %7D from 'redux-cozy-client
+* as fromCozyClient from 'redux-cozy-client'%0Aimport %7B getAccount %7D from '../accounts
 '%0A%0Ae
@@ -208,16 +208,31 @@
 () =%3E%0A  
+fromCozyClient.
 fetchCol
@@ -271,16 +271,17 @@
 OCTYPE)%0A
+%0A
 export c
@@ -368,16 +368,31 @@
 %0A) =%3E%0A  
+fromCozyClient.
 createTr
@@ -397,16 +397,21 @@
 Trigger(
+%0A    
 buildKon
@@ -461,23 +461,29 @@
 ptions),
+%0A   
  %7B%0A    
+  
 updateCo
@@ -523,10 +523,106 @@
 %5D%0A  
-%7D)
+  %7D%0A  )%0A%0Aexport const launchTrigger = trigger =%3E fromCozyClient.launchTrigger(trigger)%0A%0A// Helpers
 %0A%0Aex
@@ -1113,33 +1113,34 @@
 r',%0A      worker
-A
+_a
 rguments: worker
@@ -1161,8 +1161,646 @@
 %7D%0A  %7D%0A%7D%0A
+%0A// selectors%0A%0Aexport const getKonnectorConnectedAccount = (state, konnector) =%3E %7B%0A  // state is state.cozy%0A  const trigger = getTriggerByKonnector(state, konnector)%0A%0A  if (!trigger) return null%0A%0A  return getAccount(state, trigger.message.account)%0A%7D%0A%0Aexport const getTriggerByKonnector = (state, konnector) =%3E %7B%0A  // state is state.cozy%0A  if (!state.documents %7C%7C !state.documents%5BDOCTYPE%5D) return null%0A  const trigger = Object.values(state.documents%5BDOCTYPE%5D).find(trigger =%3E %7B%0A    return (%0A      trigger.worker === 'konnector' &&%0A      trigger.message &&%0A      trigger.message.konnector === konnector.slug%0A    )%0A  %7D)%0A%0A  return trigger%0A%7D%0A

improve trigger duck and add new methods ✨:duck: