package com.bytesw.bytebot.etl.services;

import com.bytesw.bytebot.etl.dao.SessionBotRepository;
import com.bytesw.bytebot.etl.model.Session;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Log4j2
public abstract class MessageProcessedSupport {

    protected static final String SENDER_ID_FIELD_NAME = "senderId";
    protected static final String CONTENT_FIELD_NAME = "content";
    protected static final String CONFIDENCE_FIELD_NAME = "confidence";
    protected static final String CHANNEL_FIELD_NAME = "channel";
    protected static final String TIMESTAMP_FIELD_NAME = "timestamp";
    protected static final String ACTION_FIELD_NAME = "actionName";
    protected static final String INTENT_NAME = "intentName";


    protected Map<String, String> fields = new HashMap<>();

    @Autowired
    protected SessionBotRepository sessionBotRepository;

    protected static final String PYTHON_TIMESTAMP_FORMAT = "^\\d*\\.?\\d*$";
    protected static final Pattern pattern = Pattern.compile(PYTHON_TIMESTAMP_FORMAT);

    protected OffsetDateTime getOffsetDateTimeFromTimestampPython(Object objectTimestamp) {
        BigDecimal dateDecimal;
        if (objectTimestamp instanceof Double) {
            dateDecimal = new BigDecimal((Double) objectTimestamp);
        } else {
            if (!isValidTimestampFormat(String.valueOf(objectTimestamp), pattern)) {
                return null;
            }
            dateDecimal = new BigDecimal(String.valueOf(objectTimestamp));
        }
        Long timestamp = (long) (dateDecimal.doubleValue() * 1000);
        if (String.valueOf(timestamp).length() < 13) {
            int numberOfZero = 13 - String.valueOf(timestamp).length();
            for (int i = 0; i < numberOfZero; i++) {
                timestamp = timestamp * 10;
            }
        }
        OffsetDateTime date = OffsetDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
        return date;
    }

    protected boolean isValidTimestampFormat(String text, Pattern pattern) {
        Matcher matcher = pattern.matcher(text);
        boolean matches = matcher.matches();
        return matches;
    }

    protected void updateEventDate(Long sessionId, OffsetDateTime date) {
        Optional<Session> sessionFond = sessionBotRepository.findById(sessionId);
        if (sessionFond.isPresent()) {
            Session session = sessionFond.get();
            session.setLastEventDate(date);
            sessionBotRepository.save(session);
        }
    }
}
