package com.yihu.hos.broker.services;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.core.datatype.DateUtil;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.broker.models.BusinessLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @created Airhead 2016/8/8.
 */
@Component("businessLogService")
public class BusinessLogService {
    private static final Logger logger = LoggerFactory.getLogger(BusinessLogService.class);
    @Autowired
    private MongoOperations mongoOperations;

    public void log(String msg) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            BusinessLog businessLog = objectMapper.readValue(msg, BusinessLog.class);
            String fireTimeSource = businessLog.getFireTimeSource();
            businessLog.setFireTime(DateUtil.toTimestamp(fireTimeSource));
            businessLog.setBodyLength(businessLog.getBody().length());
            mongoOperations.save(businessLog);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    }
}
