'use strict'

const config = require('./config.js')
const logger = require('./logger.js')(config)

const SearchEngines = require('./search-engines')
const Telegraf = require('telegraf')

const TEXT_WELCOME = 'Hi! Please type your search query!'
const TEXT_FOUND_BOTS = 'Found bots: '

const MAX_MESSAGE_LINES = 25

const searchEngines = new SearchEngines(logger, config)
const bot = new Telegraf(config.telegramBotToken)

bot.command('start', ctx => {
    ctx.reply(TEXT_WELCOME).catch(logger.error)
})

bot.on('message', ctx => {
    const query = ctx
        .message
        .text
        .trim()
        .toLowerCase()

    logger.info(`query="${query}" from "${ctx.from.username}" (${ctx.from.id})`)

    if (query.length === 0) {
        ctx
            .reply(TEXT_WELCOME)
            .catch(logger.error)
    } else {
        searchEngines
            .find(query)
            .then(lines => ctx
                .reply(`${TEXT_FOUND_BOTS}${lines.length}`)
                .then(() => {
                    for (let i = 0; i < lines.length; i += MAX_MESSAGE_LINES) {
                        const message = lines
                            .slice(i, i + MAX_MESSAGE_LINES)
                            .join('\n')
                        ctx
                            .reply(message)
                            .catch(logger.error)
                    }
                })
                .catch(logger.error)
            )
            .catch(logger.error)
    }
})

bot.startPolling()

@@ -1013,67 +1013,93 @@
    f
-or (let i = 0; i %3C lines.length; i += MAX_MESSAGE_LINES) %7B%0A
+unction onNextReply(index) %7B%0A                        if (index %3C lines.length) %7B%0A    
     
@@ -1172,16 +1172,20 @@
     
+    
 .slice(i
 , i 
@@ -1184,11 +1184,19 @@
 ce(i
-, i
+ndex, index
  + M
@@ -1241,16 +1241,20 @@
         
+    
 .join('%5C
@@ -1273,36 +1273,44 @@
                 
+   
+ 
 ctx%0A
+    
                 
@@ -1337,16 +1337,104 @@
 essage)%0A
+                                .then(() =%3E onNextReply(index + MAX_MESSAGE_LINES))%0A    
         
@@ -1494,17 +1494,78 @@
         
-%7D
+    %7D%0A                    %7D%0A                    onNextReply(0)
 %0A       

send messages sequentially