package xyz.luxnk.lproject.quartz.job;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import xyz.luxnk.lproject.bean.UserInfo;
import xyz.luxnk.lproject.bean.UserProfile;

import java.util.Date;

@IocBean
public class CleanNonActiveUserJob implements Job {

    private static final Log log = Logs.get();

    @Inject
    protected Dao dao;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.debug("clean Non-Active User, start");
        Date deadtime = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000L);    // 一天，测试的时候可改成1小时之类
        Cnd cnd = Cnd.where("createTime", "<", deadtime).and(Cnd.exps("emailChecked", "=", false).or("email", "IS", null));
        int deleted = dao.clear(UserProfile.class, cnd);
        log.debugf("delete %d UserProfile", deleted);

        Sql sql = Sqls.create("delete from $user_info_table where not exists (select 1 from $user_profile_table where $user_info_table.id = uid) and create_time < @deadtime");
        sql.vars().set("user_info_table", dao.getEntity(UserInfo.class).getTableName());
        sql.vars().set("user_profile_table", dao.getEntity(UserProfile.class).getTableName());
        sql.params().set("deadtime", deadtime);
        dao.execute(sql);
        log.debugf("delete %d User", sql.getUpdateCount());

        log.debug("clean Non-Active User, Done");
    }
}
