package com.tykj.workflowcore.model_layer.utils;

import com.tykj.workflowcore.model_layer.dao.TableInfoDao;
import com.tykj.workflowcore.model_layer.entity.TableInfo;
import org.checkerframework.checker.units.qual.A;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.hibernate.tool.schema.TargetType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManagerFactory;
import java.io.ByteArrayInputStream;
import java.util.EnumSet;
import java.util.List;

/**
 * @ClassName SessionUtil
 * @Description TODO
 * @Author WWW
 * @Date 2021/4/1 10:08
 * @Version 1.0
 */
@Component
public class SessionUtil {


    SessionFactory sessionFactory;

    StandardServiceRegistry serviceRegistry;

    @Autowired
    TableInfoDao tableInfoDao;

    MetadataSources metadataSources;
    public SessionUtil(EntityManagerFactory entityManagerFactory,TableInfoDao tableInfoDao){
        this.tableInfoDao = tableInfoDao;
        sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
        serviceRegistry = sessionFactory.getSessionFactoryOptions().getServiceRegistry();
        metadataSources = new MetadataSources(serviceRegistry);
        sessionFactory.getSessionFactoryOptions();
        init();
    }

    private void init(){
        //去数据库读取所有的XML 加载到 metasource里
        List<TableInfo> all = tableInfoDao.findAll();
        for (TableInfo tableInfo : all) {
            String xml = tableInfo.getXml();
            addXml(xml);
        }
    }

    public void addXml(String xmlStr){
        metadataSources.addInputStream(new ByteArrayInputStream(xmlStr.getBytes()));
        Metadata metadata = metadataSources.buildMetadata();
        //更新数据库Schema,如果不存在就创建表,存在就更新字段,不会影响已有数据
//        SchemaUpdate schemaUpdate = new SchemaUpdate();
//        schemaUpdate.execute(EnumSet.of(TargetType.DATABASE), metadata, serviceRegistry);
    }

    public Session getSession(){
        Metadata metadata = metadataSources.buildMetadata();
        //创建会话工厂
        SessionFactory newSessionFactory = metadata.buildSessionFactory();
        //保存对象
        return newSessionFactory.openSession();
    }
}
