import Rx from 'rx'
import chalk from 'chalk'

import { makeSources, makeUpdates, makeWebHook } from './sources'
import { makeAPIRequest } from './api-request'
import { Request } from './types/types'

function makeEventsSelector (sources) {
  return function events (eventName) {
    let messageSources = {
      'message': sources.message.share()
    }

    let inlineQuerySources = {
      'inline_query': sources.inlineQuery.share(),
      'chosen_inline_result': sources.chosenInlineResult.share()
    }

    let callbackQuerySources = {
      'callback_query': sources.callbackQuery.share()
    }

    // return interface
    return Rx.Observable.case(
      () => eventName,
      Object.assign({}, messageSources, inlineQuerySources, callbackQuerySources)
    )
  }
}

export function makeTelegramDriver (token, webHook) {
  let proxy = webHook ? makeWebHook(token, webHook) : makeUpdates(token)
  let updates = proxy
    .doOnError(err => console.log('Updates Error', err))
    .replay(null, 1)

  let sources = makeSources(updates)
  let disposable = updates.connect()

  return function telegramDriver (request) {
    // pass request
    request
      .mergeAll()
      .filter(Request.is)
      .flatMap(({method, options: query}) => makeAPIRequest({token, method, query}))
      .subscribe(
        msg => console.log(chalk.bold('sent message')),
        err => console.log('onError', err)
      )

    // return interface
    return {
      observable: updates,
      events: makeEventsSelector(sources),
      dispose: () => disposable.dispose()
    }
  }
}

@@ -16,34 +16,8 @@
 'rx'
-%0Aimport chalk from 'chalk'
 %0A%0Aim
@@ -153,22 +153,17 @@
  from '.
-/types
+.
 /types'%0A
@@ -738,16 +738,277 @@
 %0A  %7D%0A%7D%0A%0A
+let handleRequest = (token, request) =%3E %7B%0A  return request%0A    .mergeAll()%0A    .filter(Request.is)%0A    .flatMap((%7Bmethod, options: query%7D) =%3E makeAPIRequest(%7Btoken, method, query%7D))%0A    .doOnError(err =%3E console.log('request error: ', err))%0A    .subscribe()%0A%7D%0A%0A
 export f
@@ -1187,21 +1187,23 @@
 og('
-U
+u
 pdates 
-E
+e
 rror
+: 
 ', e
@@ -1377,120 +1377,22 @@
     
-request%0A      .mergeAll()%0A      .filter(Request.is)%0A      .flatMap((%7Bmethod, options: query%7D) =%3E makeAPI
+handle
 Request(
 %7Btok
@@ -1391,156 +1391,22 @@
 est(
-%7B
 token, 
-method, query%7D))%0A      .subscribe(%0A        msg =%3E console.log(chalk.bold('sent message')),%0A        err =%3E console.log('onError', err)%0A      
+request
 )%0A%0A 

split request handle