package com.ffii.lioner.modules.lioner.userActionLog.service;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.ffii.core.support.AbstractBaseEntityService;
import com.ffii.core.support.JdbcDao;
import com.ffii.core.utils.BeanUtils;
import com.ffii.lioner.modules.lioner.userActionLog.entity.UserActionLogRepository;
import com.ffii.lioner.modules.lioner.userActionLog.req.UpdateUserActionLogReq;
import com.ffii.lioner.modules.common.SecurityUtils;
import com.ffii.lioner.modules.lioner.userActionLog.entity.UserActionLog;

@Service
public class UserActionLogService extends AbstractBaseEntityService<UserActionLog, Long, UserActionLogRepository> {

	public UserActionLogService(JdbcDao jdbcDao, UserActionLogRepository repository) {
		super(jdbcDao, repository);
	}

	public void createLog(String actionDesc, Long refId, String refType) {
		UserActionLog userActionLog = new UserActionLog();
        userActionLog.setUsername(SecurityUtils.getUser().get().getUsername());
        userActionLog.setActionDesc(actionDesc);
        userActionLog.setRefId(refId);
        userActionLog.setRefType(refType);
        save(userActionLog);
	}

	public Map<String, Object> saveOrUpdate(UpdateUserActionLogReq req) {
		UserActionLog instance;
		// List<SubDivision> onUsingIdList = new ArrayList<SubDivision>();
		if (req.getId() > 0){
			instance = find(req.getId()).get();
		}
		else {
			instance = new UserActionLog();
		}

		BeanUtils.copyProperties(req,instance);

		instance = save(instance);
				
		return Map.of(
			"id", instance.getId()
		);
	}

	public List<Map<String,Object>> list(Map<String, Object> args){
			StringBuilder sql = new StringBuilder("SELECT"
				+ " user_action_log.actionDesc, "
				+ " user_action_log.created, "
				+ " user.fullname, "
				+ " user.username "
				+ " from user_action_log "
				+ " left join user on user_action_log.username = user.username "
				+ " WHERE user_action_log.deleted = FALSE "

		);

		if (args != null) {
			if (args.containsKey("username")) sql.append(" AND user_action_log.username = :username");
			if (args.containsKey("actionDesc")) sql.append(" AND user_action_log.actionDesc like :actionDesc");
			if (args.containsKey("fromDate"))sql.append(" AND user_action_log.created >= :fromDate");
			if (args.containsKey("toDate"))sql.append(" AND user_action_log.created < :toDate");
		}
				
		// }
		sql.append(" ORDER BY user_action_log.id desc ");

		return jdbcDao.queryForList(sql.toString(), args);
	}

	
}