'use strict'
const TgClient = require('node-telegram-bot-api')
const fs = require('fs')
const fetch = require('node-fetch')
const Promise = require('bluebird')
require('dotenv').config()

const TG_API_TOKEN = process.env.TG_API_TOKEN
const IMAGE_URLS = ['http://haba.tko-aly.fi/kuvat/webcam1.jpg', 'http://haba.tko-aly.fi/kuvat/webcam2.jpg']
const WEBHOOK_PORT = parseInt(process.env.PORT || '1234', 10)

const client = createClient()
client.onText(/\/cams/, camsCommand)


function createClient() {
    console.log(`HEROKU_APP_NAME: ${process.env.HEROKU_APP_NAME}, WEBHOOK_PORT: ${process.env.WEBHOOK_PORT}`)
    if (process.env.HEROKU_APP_NAME) {
        const client = new TgClient(TG_API_TOKEN, {
            webHook: {
                port: WEBHOOK_PORT
            }
        })
        client.setWebHook(`https://${process.env.HEROKU_APP_NAME}.herokuapp.com/bot${TG_API_TOKEN}`)
        return client
    } else {
        return new TgClient(TG_API_TOKEN, {
            polling: true
        })
    }
}

function camsCommand(msg) {
    client.sendPhoto(msg.chat.id, `${IMAGE_URLS[0]}?nocacheplz=${new Date().getTime()}`)
    client.sendPhoto(msg.chat.id, `${IMAGE_URLS[1]}?nocacheplz=${new Date().getTime()}`)
}

@@ -384,16 +384,17 @@
 .PORT %7C%7C
+ 
 %C2%A0'1234',
@@ -399,16 +399,90 @@
 ', 10)%0A%0A
+console.log(%60Starting bot%60)%0Aconsole.log(%60Webhook port: $%7BWEBHOOK_PORT%7D%60)%0A%0A
 const cl
@@ -541,17 +541,16 @@
 mmand)%0A%0A
-%0A
 function
@@ -575,152 +575,89 @@
     
-console.log(%60HEROKU_APP_NAME: $%7Bprocess.env.HEROKU_APP_NAME%7D, WEBHOOK_PORT: $%7Bprocess.env.WEBHOOK_PORT%7D%60)%0A    if (process.env.HEROKU_APP_NAME) %7B
+if (process.env.HEROKU_APP_NAME) %7B%0A        console.log('Creating webhook client')
 %0A   
@@ -924,16 +924,63 @@
  else %7B%0A
+        console.log('Creating polling client')%0A
         
@@ -1065,39 +1065,346 @@
 %0A%7D%0A%0A
-function camsCommand(msg) %7B%0A   
+const EIGHT_S_TO_MS = 8 / 1000%0Aconst chatIdToPreviousSentTimestamp = %7B%7D%0A%0Aconst allowedToSendToChatAlready = id =%3E %7B%0A    const prevTimestamp = chatIdToPreviousSentTimestamp%5Bid%5D%0A    if (!prevTimestamp) return true%0A%0A    const now = new Date()%0A    return (now - prevTimestamp) %3E= EIGHT_S_TO_MS%0A%7D%0A%0Aconst createSendPhoto = chatId =%3E imageUrl =%3E
  cli
@@ -1421,49 +1421,88 @@
 oto(
-msg.
 chat
-.id, %60$%7BIMAGE_URLS%5B0%5D%7D?
+Id, imageUrl)%0Aconst concatCacheBuster = url =%3E %60$%7Burl%7D?telegram_plz_
 no
+_
 cache
-plz
 =$%7Bn
@@ -1526,97 +1526,244 @@
 ()%7D%60
-)%0A    client.sendPhoto(msg.chat.id, %60$%7BIMAGE_URLS%5B1%5D%7D?nocacheplz=$%7Bnew Date().getTime()%7D%60
+%0Aconst getImageUrls = () =%3E IMAGE_URLS.map(concatCacheBuster)%0A%0Afunction camsCommand(msg) %7B%0A    if (!allowedToSendToChatAlready(msg.chat.id)) return%0A%0A    const sendPhoto = createSendPhoto(msg.chat.id)%0A    getImageUrls().forEach(sendPhoto
 )%0A%7D%0A

Implement flood control per-chat, add logging