package jp.sourceforge.shovel.service.impl;

import javax.transaction.Transaction;
import javax.transaction.TransactionManager;

import org.seasar.framework.container.S2Container;
import org.seasar.framework.container.factory.SingletonS2ContainerFactory;

import jp.sourceforge.shovel.SizeType;
import jp.sourceforge.shovel.entity.IServerFile;
import jp.sourceforge.shovel.exception.ApplicationException;
import jp.sourceforge.shovel.logic.IServerFileLogic;
import jp.sourceforge.shovel.service.IServerFileService;
import jp.sourceforge.shovel.xa.XAServerFile;

public class ServerFileServiceImpl implements IServerFileService {
    public void createServerFile(IServerFile serverFile, boolean thumbnail, boolean detectEncoding) throws ApplicationException {
        if (serverFile.isExists()) {
            getServerFileLogic().createServerFile(serverFile, thumbnail, detectEncoding);
            getXAResource().addToCopy(serverFile);
        }
    }
    public void removeServerFile(IServerFile serverFile) throws ApplicationException {
        getXAResource().addToRemove(serverFile);
        getServerFileLogic().removeServerFile(serverFile.getServerFileId());
    }
    public boolean createThumbnail(IServerFile serverFile, SizeType sizeType) throws ApplicationException {
        if (!serverFile.isExists(sizeType) && !sizeType.isOriginal()) {
            getServerFileLogic().createThumbnail(serverFile, sizeType);
            getXAResource().addToWork(serverFile, sizeType);
            return true;
        }
        return false;
    }
    
    TransactionManager getTransactionManager() {
        return (TransactionManager)getContainer().getComponent(TransactionManager.class);
    }
    
    XAServerFile xa_;
    
    XAServerFile getXAResource() throws ApplicationException {
        if (xa_ == null) {
            try {
                Transaction tx = getTransactionManager().getTransaction();
                xa_ = (XAServerFile)getContainer().getComponent(XAServerFile.class);
                tx.enlistResource(xa_);
            } catch(Exception cause) {
                //TODO
                ApplicationException e = new ApplicationException("");
                e.initCause(cause);
                throw e;
            }
        }
        return xa_;
    }
    
    /////
    
    S2Container getContainer() {
        return SingletonS2ContainerFactory.getContainer();
    }
    
    IServerFileLogic serverFileLogic_;
    TransactionManager transactionManager_;
    
    public void setServerFileLogic(IServerFileLogic serverFileLogic) {
        serverFileLogic_ = serverFileLogic;
    }
    IServerFileLogic getServerFileLogic() {
        return serverFileLogic_;
    }
    public void setTransactionManager(TransactionManager transactionManager) {
        transactionManager_ = transactionManager;
    }
}
