package com.jasamedika.medifirst2000.logging;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.jasamedika.medifirst2000.base.BaseMaster;
import com.jasamedika.medifirst2000.base.BaseTransaction;
import com.jasamedika.medifirst2000.dao.ActivityLogRepository;
import com.jasamedika.medifirst2000.entities.ActivityLog;
import com.jasamedika.medifirst2000.entities.LoginUser;
import com.jasamedika.medifirst2000.service.LoginUserService;

/**
 * 
 * @author Hutagalung
 */
@Aspect
public class LoggingAdvise {
	
	private final Logger LOG = LoggerFactory.getLogger(LoggingAdvise.class);

	@Autowired
	private ActivityLogRepository activityLogRepository;
	
	@Autowired
	private LoginUserService loginUserService;
	
	private StringBuffer buffer, detail;

	/*@AfterReturning("execution(* com.jasamedika.medifirst2000.service.*.add(*)) && args(object)")
	public void logAddAction(JoinPoint jp, Object object) throws Throwable {
		logActivity(" creates new data: ", object);
	}*/
	
	@AfterReturning("execution(* com.jasamedika.medifirst2000.dao.*.save(*)) && args(object)")
    public void logUpdateAction(JoinPoint jp, Object object) throws Throwable {
		logActivity(object);
    }
	
	private void logActivity(Object object) {
		// get current user
		LoginUser currentUser = loginUserService.getLoginUser();
		
		buffer = new StringBuffer();
		buffer.append(currentUser.getNamaUser());
		
		// checking action
		if (object instanceof BaseMaster) {/*
			if (((BaseMaster) object).getId() == null) {
				buffer.append(" inserts master record ");
			} else {
				buffer.append(" updates master record ");
			}
		*/} else if (object instanceof BaseTransaction) {
			if (((BaseTransaction) object).getNoRec().isEmpty()) {
				buffer.append(" insert transaction record ");
			} else {
				buffer.append(" updates transactionr record ");
			}
		}
		
		
		detail = new StringBuffer();
		try {
			detail.append(ObjectUtil.getColumnNamesAndValues(object));
		} catch(IllegalAccessException | IllegalArgumentException e) {
			LOG.error("LogActivity exception: {}", e.getMessage());
		}
		
		ActivityLog activityLog = new ActivityLog();
		activityLog.setAction(buffer.toString());
		activityLog.setDetail(detail.toString());
		activityLogRepository.save(activityLog);
	}
	
	
}
