package com.tykj.model.utils;

import com.google.common.base.Strings;


import com.tykj.model.dao.TableInfoDao;

import com.tykj.model.entity.TableInfo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmHibernateMapping;
import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmRootEntityType;
import org.hibernate.boot.jaxb.spi.Binding;
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();
        init();
    }

    public void init(){
        metadataSources = new MetadataSources(serviceRegistry);
        //去数据库读取所有的XML 加载到 metasource里
        List<TableInfo> all = tableInfoDao.findAll();
        for (TableInfo tableInfo : all) {
            String xml = tableInfo.getXml();
            if (!Strings.isNullOrEmpty(xml)){
                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();
    }

    public Metadata getMetadata(){
        return metadataSources.buildMetadata();
    }

    public MetadataSources getMetadataSources() {
        return metadataSources;
    }

    public void deleteTableInMeteData(String tableName){
        int needDelete = -1;
        List<Binding> xmlBindings = metadataSources.getXmlBindings();
        for (int i = 0; i < xmlBindings.size(); i++) {
            Object root = xmlBindings.get(i).getRoot();
            if (root instanceof JaxbHbmHibernateMapping){
                List<JaxbHbmRootEntityType> listEntity = ((JaxbHbmHibernateMapping) root).getClazz();
                for (JaxbHbmRootEntityType jaxbHbmRootEntityType : listEntity) {
                    String currentTableName = jaxbHbmRootEntityType.getTable();
                    if (currentTableName.equals(tableName)){
                        needDelete = i;
                        break;
                    }
                }

            }
        }
        if (needDelete>-1){
            xmlBindings.remove(needDelete);
        }
        System.out.println("1");
    }
}

