package jp.sourceforge.shovel.logic.impl;

import java.io.File;

import org.seasar.framework.container.S2Container;


import jp.sourceforge.shovel.dao.IMimeTypeDao;
import jp.sourceforge.shovel.entity.IMimeType;
import jp.sourceforge.shovel.exception.ApplicationException;
import jp.sourceforge.shovel.logic.IMimeTypeLogic;

public class MimeTypeLogicImpl implements IMimeTypeLogic {
    S2Container container;

    private String getExtension( String fileName )
    {
        File f = new File( fileName );
        if( f == null ) return null;

        String name = f.getName();
        int last = name.lastIndexOf( "." );
        if( last <= 0 ) return null;

        return name.substring( last );
    }
    public IMimeType getMimeTypeByFileName( String fileName )
    {
        String extension = this.getExtension( fileName );
        if( extension == null ) return null;

        return this.getMimeType( extension );
    }
    public IMimeType getMimeType( String extension )
    {
        IMimeTypeDao dao = this.getMimeTypeDao();
        return dao.findByName( extension );
    }
    public IMimeType[] getMimeTypeList( long offset, long limit )
    {
        IMimeTypeDao dao = this.getMimeTypeDao();
        return dao.findAll( offset, limit );
    }
    public void addMimeType( IMimeType mime ) throws ApplicationException {
        IMimeTypeDao dao = this.getMimeTypeDao();
        IMimeType o = dao.findByName( mime.getExtension() );
        if( o != null )
        {
            throw new ApplicationException("");
        }
        dao.insert( mime );
    }
    public void addMimeType( String extension, String mimeType ) throws ApplicationException
    {
        IMimeType mime = (IMimeType)this.container.getComponent( IMimeType.class );
        mime.setExtension( extension );
        mime.setMimeType( mimeType );
        this.addMimeType( mime );
    }
    public void removeMimeType( long[] mimeTypeIds )
    {
        if( mimeTypeIds == null || mimeTypeIds.length <= 0 ) return;

        IMimeTypeDao dao = this.getMimeTypeDao();
        dao.deleteByIds( mimeTypeIds );
    }
    public void updateMimeType( IMimeType mime )
    {
        IMimeTypeDao dao = this.getMimeTypeDao();
        dao.update( mime );
    }

    IMimeTypeDao getMimeTypeDao()
    {
        return (IMimeTypeDao)this.container.getComponent( IMimeTypeDao.class );
    }
    public void setContainer( S2Container container )
    {
        this.container = container;
    }
}
