package com.yihu.hos.interceptor;

import com.yihu.hos.common.constants.ContextAttributes;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.EmptyInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/11/30.
 */
@Component
public class AuditInterceptor extends EmptyInterceptor {

    private static final long serialVersionUID = 1L;
    private static Logger logger = LoggerFactory.getLogger(AuditInterceptor.class);

    @Override
    public String onPrepareStatement(String sql) {

        if(null!=sql && sql.contains("mycat:schema=")){
            return super.onPrepareStatement(sql);
        }

        String schemaName = getSchema();
        String completeSql = sql;
        if (StringUtils.isNotEmpty(schemaName)) {
            String myCatAnnotation = "/*#mycat:schema=" + schemaName + "*/ ";
            completeSql = myCatAnnotation + sql;
        }
//        logger.info("prepare " + completeSql);
        return super.onPrepareStatement(completeSql);
    }

//    @Override
//    public void onDelete(
//            Object entity,
//            Serializable id,
//            Object[] state,
//            String[] propertyNames,
//            Type[] types) {
//        System.out.println("33333333333333");
//        super.onDelete(entity,id,state,propertyNames,types);
//    }


//    @Override
//    public void preFlush(Iterator entities) {
//        System.out.println("preflush..............");
//        super.preFlush(entities);
//    }

    private String getSchema() {
        return LocalContext.getContext().getAttachment(ContextAttributes.SCHEMA);
    }

}
