/* Copyright 2008 we-lab-doc! (http://www.we-lab-doc.com/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.we_lab_doc.spacecard.model.abstracts

import com.we_lab_doc.spacecard.utils.*

/**
 * @author Shigeru GOUGI
 * @since 0.1
 *        <p/>
 *        Created: February 13, 2008
 */ 
abstract class AttachedFile extends Attachment {
	def attachedFileManager
	
	boolean remove() {
		if(super.remove()) {
			attachedFileManager.disposeIfNeeds(this)
			// TODO: 本来はHibernateのイベントで処理する。Grailsの不具合が直って対応
			return true
		} else {
			return false
		}
	}
	boolean hasByteArray() {
		byteArray != null
	}
	boolean hasFileURL() {
		fileURL != null
	}
	/////////////////////////////////////////////
	protected String makeContentType(fileName){
		assert fileName != null		
		log.debug("makeContentType: fileName = ${fileName}")
		def mimeTypes = MimeTypesUtils.getMimeTypes()
		def suffix = FileUtils.getSuffix(fileName).toLowerCase()
		def mimeType = mimeTypes."${suffix}"
		if(mimeType == null)
			log.debug("mimeTypes: ${mimeTypes}")
		log.debug("makeContentType: suffix = ${suffix}, mimeType = ${mimeType}")
		return mimeType ? mimeType : "binary/octet-stream"
	}
	/////////////////////////////////////////////
	static constraints = {
		byteArray(nullable:true)
		fileURL(nullable:true)		 
		contentType(blank:false)
		fileName(blank:false)
	}
	/////////////////////////////////////////////
	byte[] byteArray
	URL    fileURL
	// byteArray か fileUrl のどちらか一方にアップロード
	String contentType
	String fileName
}
