package com.bytesw.bytebot.etl.services;

import com.bytesw.bytebot.etl.dao.UserRepository;
import com.bytesw.bytebot.etl.model.Session;
import com.bytesw.bytebot.etl.model.User;
import com.bytesw.bytebot.etl.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.transaction.Transactional;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

@Service
@Transactional
public class StartSessionMessageProcessed extends MessageProcessedSupport implements MessageProcessed {

    @Autowired
    private UserRepository userRepository;

    @PostConstruct
    private void init() {
        this.fields.put(SENDER_ID_FIELD_NAME, "$.sender_id");
        this.fields.put(TIMESTAMP_FIELD_NAME, "$.timestamp");
    }

    @Override
    public boolean process(String json, String oldSenderId) {
        String senderId = oldSenderId != null ? oldSenderId : (String) JsonUtils.getFieldFromJson(json, this.fields.get(SENDER_ID_FIELD_NAME));

        if (senderId != null) {
            Optional<User> userFound = userRepository.findByIdentifier(senderId);
            User user;
            if (!userFound.isPresent()) {
                user = new User();
                user.setIdentifier(senderId);
                user = userRepository.save(user);
            } else {
                user = userFound.get();
            }

            Double timestamp = (Double) JsonUtils.getFieldFromJson(json, this.fields.get(TIMESTAMP_FIELD_NAME));

            if (timestamp != null) {
                // Validate if the below method is ok
                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSX");
                OffsetDateTime sessionDate = getOffsetDateTimeFromTimestampPython(timestamp);
                if (sessionDate != null) {
                    Session session = new Session();
                    session.setSessionDate(sessionDate);
                    session.setUser(user);
                    session.setLastEventDate(sessionDate);
                    sessionBotRepository.save(session);
                    return true;
                }
            }
        }


        return false;
    }


}

