package com.teemlink.sync.service;

import cn.myapps.authtime.common.dao.PersistenceUtils;
import cn.myapps.common.dao.datasource.FileSystemDataSourceDAO;
import cn.myapps.common.model.datasource.DataSource;
import com.teemlink.sync.dao.SyncDao;
import com.teemlink.sync.model.DataOperation;
import org.springframework.stereotype.Service;

import javax.naming.NamingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

@Service
public class SyncServiceImpl implements SyncService{

    @Override
    public void syncData(DataOperation dataPackage) throws Exception {
        String action = dataPackage.getAction();
        switch (action){
            case DataOperation.ACT_CREATE :
                getDao(dataPackage).create(dataPackage.getDataObject());
                break;
            case DataOperation.ACT_UPDATE :
                getDao(dataPackage).update(dataPackage.getDataObject());
                break;
            case DataOperation.ACT_DELETE :
                getDao(dataPackage).delete(dataPackage.getDataObject());
                break;
        }

    }

    /**
     * 获取dao
     * @param dataPackage
     * @return
     */
    private SyncDao getDao(DataOperation dataPackage){
        SyncDao syncDao = null;
        try {
            FileSystemDataSourceDAO dataSourceDao = new FileSystemDataSourceDAO(DataSource.class);
            DataSource dataSource = dataSourceDao.getDataSource(dataPackage.getDataSourceName(), dataPackage.getApplicationId());
            Connection connection = getConnection(dataSource);
            syncDao = new SyncDao(connection);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return syncDao;
    }

    /**
     * 获取连接
     */
    private Connection getConnection(DataSource dataSource) throws NamingException, SQLException,
            InstantiationException, IllegalAccessException,
            ClassNotFoundException {
        Connection connection = null;
        if (DataSource.TYPE_JNDI.equals(dataSource.getUseType())) {
            connection = dataSource.getJNDIConnection();
        } else {
            String url = dataSource.getUrl();
            String driver = dataSource.getDriverClass();
            connection = PersistenceUtils.getDruidDataSource(
                    "SyncServiceImpl",
                    dataSource.getUsername(), dataSource.getPassword(), driver, url, "100", "3000")
                    .getConnection();
        }

        return connection;
    }

}
