/*
 * Copyright 2019 - 2020 Anton Tananaev (anton@traccar.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.traccar.notificators;

import com.fasterxml.jackson.annotation.JsonProperty;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.traccar.Context;
import org.traccar.config.Keys;
import org.traccar.model.Event;
import org.traccar.model.Position;
import org.traccar.notification.NotificationFormatter;

import javax.ws.rs.client.Entity;
import javax.ws.rs.client.InvocationCallback;

public class NotificatorTelegram extends Notificator {

    private static final Logger LOGGER = LoggerFactory.getLogger(NotificatorTelegram.class);

    private final String urlSendText;
    private final String urlSendLocation;
    private final String chatId;

    public static class Message {
        @JsonProperty("chat_id")
        private String chatId;
        @JsonProperty("text")
        private String text;
        @JsonProperty("parse_mode")
        private String parseMode = "html";
    }

    public static class LocationMessage {
        @JsonProperty("chat_id")
        private String chatId;
        @JsonProperty("latitude")
        private double latitude;
        @JsonProperty("longitude")
        private double longitude;
        @JsonProperty("horizontal_accuracy")
        private double accuracy;
        @JsonProperty("bearing")
        private double bearing;
        @JsonProperty("parse_mode")
        private String parseMode = "html";
    }

    public NotificatorTelegram() {
        urlSendText = String.format(
                "https://api.telegram.org/bot%s/sendMessage",
                Context.getConfig().getString(Keys.NOTIFICATOR_TELEGRAM_KEY));
        urlSendLocation = String.format(
                "https://api.telegram.org/bot%s/sendLocation",
                Context.getConfig().getString(Keys.NOTIFICATOR_TELEGRAM_KEY));
        chatId = Context.getConfig().getString(Keys.NOTIFICATOR_TELEGRAM_CHAT_ID);
    }

    @Override
    public void sendSync(long userId, Event event, Position position) {

        Message message = new Message();
        message.chatId = chatId;
        message.text = NotificationFormatter.formatFullMessage(userId, event, position);
        executeRequest(urlSendText, message);

        if (position != null) {
            LocationMessage locationMessage = new LocationMessage();
            locationMessage.chatId = chatId;
            locationMessage.latitude = position.getLatitude();
            locationMessage.longitude = position.getLongitude();
            locationMessage.bearing = position.getCourse();
            locationMessage.accuracy = position.getAccuracy();
            executeRequest(urlSendLocation, locationMessage);
        }
    }

    @Override
    public void sendAsync(long userId, Event event, Position position) {
        sendSync(userId, event, position);
    }

    private void executeRequest(String url, Object message) {
        Context.getClient().target(url).request()
                .async().post(Entity.json(message), new InvocationCallback<Object>() {
            @Override
            public void completed(Object o) {
            }

            @Override
            public void failed(Throwable throwable) {
                LOGGER.warn("Telegram API error", throwable);
            }
        });
    }

}

@@ -948,16 +948,50 @@
 atter;%0A%0A
+import javax.annotation.Nullable;%0A
 import j
@@ -1351,16 +1351,20 @@
 c class 
+Text
 Message 
@@ -1484,24 +1484,126 @@
 tring text;%0A
+        @Nullable%0A        @JsonProperty(%22reply_to_message_id%22)%0A        private Long replyToMessageId;%0A
         @Jso
@@ -2049,101 +2049,19 @@
 ate 
-double bearing;%0A        @JsonProperty(%22parse_mode%22)%0A        private String parseMode = %22html%22
+int bearing
 ;%0A  
@@ -2559,300 +2559,542 @@
     
-@Override%0A    public void sendSync(long userId, Event event, Position position) %7B%0A%0A        Message 
+private void executeRequest(String url, Object message) %7B%0A        Context.getClient().target(url).request()%0A                .async().post(Entity.json(
 message
- =
+),
  new 
-Message();%0A        message.chatId = chatId;%0A        message.text = NotificationFormatter.formatFullMessage(userId, event, position);%0A        executeRequest(urlSendText, message);%0A
+InvocationCallback%3CObject%3E() %7B%0A            @Override%0A            public void completed(Object o) %7B%0A            %7D%0A%0A            @Override%0A            public void failed(Throwable throwable) %7B%0A                LOGGER.warn(%22Telegram API error%22, throwable);%0A            %7D%0A        %7D);%0A    %7D%0A%0A    @Override%0A    public void sendSync(long userId, Event event, Position position) %7B
 %0A   
@@ -3402,16 +3402,32 @@
 aring = 
+(int) Math.ceil(
 position
@@ -3438,16 +3438,17 @@
 Course()
+)
 ;%0A      
@@ -3584,438 +3584,340 @@
     
-%7D%0A%0A
     
-@Override%0A    public void sendAsync(long userId, Event event, Position position) %7B%0A        sendSync(userId, event, position)
+TextMessage message = new TextMessage();%0A        message.chatId = chatId
 ;%0A    
-%7D%0A%0A
     
-private void executeRequest(String url, Object message) %7B%0A        Context.getClient().target(url).request()%0A                .async().post(Entity.json(message), new InvocationCallback%3CObject%3E() %7B%0A            @Override%0A            public void completed(Object o) %7B%0A        
+// message.replyToMessageId = Long.MIN_VALUE; TODO add message ID from the first request here%0A        message.text = NotificationFormatter.formatFullMessage(userId, event, position).getBody();%0A        executeRequest(urlSendText, message);%0A
     %7D%0A%0A
-        
     
@@ -3922,32 +3922,24 @@
   @Override%0A
-        
     public v
@@ -3946,123 +3946,105 @@
 oid 
-failed(Throwable throwable) %7B%0A                LOGGER.warn(%22Telegram API error%22, throwable);%0A            %7D%0A        %7D
+sendAsync(long userId, Event event, Position position) %7B%0A        sendSync(userId, event, position
 );%0A 

prepare NotificatorTelegram to send coupled messages; fix data class field types