package com.wutiarn.flibustabot.service;

import com.pengrad.telegrambot.model.Chat;
import com.pengrad.telegrambot.model.Message;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.model.request.ParseMode;
import com.pengrad.telegrambot.request.BaseRequest;
import com.pengrad.telegrambot.request.SendMessage;
import com.pengrad.telegrambot.response.BaseResponse;
import com.wutiarn.flibustabot.model.opds.BookSearchResult;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;

@Service
public class TelegramEventsRouterService {
    Logger logger = LoggerFactory.getLogger(TelegramEventsRouterService.class);

    final FlibustaService flibustaService;

    @Autowired
    Configuration freemarkerConfiguration;

    @Autowired
    public TelegramEventsRouterService(FlibustaService flibustaService) {
        this.flibustaService = flibustaService;
    }

    public BaseRequest<? extends BaseRequest, ? extends BaseResponse> processUpdate(Update update) {
        Message message = update.message();
        if (message == null || message.chat().type() != Chat.Type.Private) {
            return null;
        }

        if (message.text() != null) {
            return handleSearchRequest(message);
        }
        return null;
    }

    private BaseRequest<? extends BaseRequest, ? extends BaseResponse> handleSearchRequest(Message message) {
        String query = message.text();
        BookSearchResult searchResults = flibustaService.search(query, FlibustaService.SearchType.BOOKS);

        var data = new HashMap<String, Object>();
        data.put("results", searchResults);

        String renderedResult;

        try {
            Template template = freemarkerConfiguration.getTemplate("searchResults.ftl");

            ByteArrayOutputStream resultStream = new ByteArrayOutputStream();
            OutputStreamWriter writer = new OutputStreamWriter(resultStream);
            template.process(data, writer);

            writer.close();
            renderedResult = resultStream.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return new SendMessage(message.chat().id(), renderedResult).parseMode(ParseMode.HTML);
    }
}

@@ -788,16 +788,80 @@
 HashMap;
+%0Aimport java.util.regex.Matcher;%0Aimport java.util.regex.Pattern;
 %0A%0A@Servi
@@ -910,16 +910,24 @@
 e %7B%0A    
+private 
 Logger l
@@ -1043,30 +1043,23 @@
 e;%0A%0A    
-@Autowired%0A   
+private
  Configu
@@ -1176,16 +1176,55 @@
 aService
+, Configuration freemarkerConfiguration
 ) %7B%0A    
@@ -1267,16 +1267,80 @@
 ervice;%0A
+        this.freemarkerConfiguration = freemarkerConfiguration;%0A
     %7D%0A%0A 
@@ -1608,38 +1608,199 @@
     
-if (message.text() != null) %7B%0A
+String messageText = message.text();%0A        if (messageText != null) %7B%0A            if (messageText.startsWith(%22/%22)) %7B%0A                return handleCommand(message);%0A            %7D else %7B%0A    
     
@@ -1836,32 +1836,46 @@
 quest(message);%0A
+            %7D%0A
         %7D%0A      
@@ -2853,11 +2853,833 @@
 );%0A    %7D
+%0A%0A    private BaseRequest%3C? extends BaseRequest, ? extends BaseResponse%3E handleCommand(Message message) %7B%0A        String messageText = message.text();%0A        String command = messageText.split(%22 %22)%5B0%5D;%0A%0A        if (command.startsWith(%22/dl_%22)) %7B%0A            var regex = Pattern.compile(%22/dl_(?%3Cformat%3E%5C%5Cw+)_(?%3Cid%3E%5C%5Cd+)%22);%0A            Matcher matcher = regex.matcher(command);%0A            if (matcher.matches()) %7B%0A                return handleBookDownload(message, matcher.group(%22format%22), matcher.group(%22id%22));%0A            %7D else %7B%0A                return new SendMessage(message.chat().id(), %22Unsupported command%22);%0A            %7D%0A        %7D%0A%0A        return null;%0A    %7D%0A%0A    BaseRequest%3C? extends BaseRequest, ? extends BaseResponse%3E handleBookDownload(Message message, String format, String id) %7B%0A        return null;%0A    %7D
 %0A%7D%0A

Handle commands