/**
 * Copyright (c) 2006, yher2.net
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, 
 *   this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation 
 *   and/or other materials provided with the distribution.
 * * Neither the name of the nor the names of its contributors may be used to endorse or 
 *   promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
 * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 
 * SUCH DAMAGE.
 */
package net.yher2.workstyle.manager;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import net.yher2.workstyle.FileData;
import net.yher2.workstyle.exception.NotFoundException;
import net.yher2.workstyle.torque.AttachedFile;
import net.yher2.workstyle.torque.File;
import net.yher2.workstyle.torque.FilePeer;
import net.yher2.workstyle.torque.TaskFileRelation;
import net.yher2.workstyle.torque.TaskFileRelationPeer;
import net.yher2.workstyle.torque.bean.FileBean;

import org.apache.torque.NoRowsException;
import org.apache.torque.TorqueException;
import org.apache.torque.util.Criteria;

public class FileManager {
	private Connection con = null;
	
	public FileManager(Connection con) {
		this.con = con;
	}
	
	public FileData getFile(int fileId) throws NotFoundException, TorqueException, IOException {
		try {
			File dbFile = getDBModel(fileId);
			java.io.File sysFile = new java.io.File(dbFile.getPath());
			
			FileData file = new FileData();
			file.setName(dbFile.getName());
			if (dbFile.getPath().length() >= dbFile.getName().length()) {
				file.setDirPath(dbFile.getPath().substring(0, dbFile.getPath().length() - file.getName().length()));
			} else {
				file.setDirPath("");
			}
			
			BufferedInputStream input = new BufferedInputStream(new FileInputStream(sysFile));
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			
			byte buf[] = new byte[256];
	        int len;
	        while ((len = input.read(buf)) != -1) {
	            output.write(buf, 0, len);
	        }
	        output.flush();
	        output.close();
	        input.close();
	        
	        file.setData(output.toByteArray());
			
			return file;
		} catch (FileNotFoundException e) {
			throw new NotFoundException("指定のファイル("+fileId+")");
		}
	}
	protected FileBean add(int taskId, FileData file) throws TorqueException, IOException {
		File dbFile = new File();
		dbFile.setName(file.getName());
		dbFile.setPath(file.getDirPath());
		
		FilePeer.doInsert(dbFile, con);
		dbFile.setPath(dbFile.getPath() + dbFile.getFileId() + file.getExtension());
		FilePeer.doUpdate(dbFile, con);
		
		TaskFileRelation relation = new TaskFileRelation();
		relation.setTaskId(taskId);
		relation.setFileId(dbFile.getFileId());
		TaskFileRelationPeer.doInsert(relation, con);
		
		java.io.File dir = new java.io.File(file.getDirPath());
		dir.mkdirs();
		
		java.io.File systemFile = new java.io.File(dbFile.getPath());
		FileOutputStream out = new FileOutputStream(systemFile);
		out.write(file.getData());
		out.flush();
		out.close();
		
		return dbFile.getBean();
	}
	
	public void delete(int fileId) throws TorqueException {
		try {
			File dbFile = getDBModel(fileId);
			List<File> fileList = new ArrayList<File>();
			fileList.add(dbFile);
			delete(fileList);
		} catch (NotFoundException e) {
			// 存在しない場合は何もしない。
		}
	}
	protected void delete(List<File> fileList) throws TorqueException {
		if (fileList.size() == 0) return;
		List<Integer> fileIdList = new ArrayList<Integer>();
		for (File file : fileList) {
			fileIdList.add(file.getFileId());
		}
		deleteRelation(fileIdList);
		deleteFile(fileIdList);
		for (File file : fileList) {
			java.io.File sysFile = new java.io.File(file.getPath());
			sysFile.delete();
		}
	}
	
	protected void deleteAttachedFile(List<AttachedFile> fileList) throws TorqueException {
		if (fileList.size() == 0) return;
		List<Integer> fileIdList = new ArrayList<Integer>();
		for (AttachedFile file : fileList) {
			fileIdList.add(file.getFileId());
		}
		
		deleteRelation(fileIdList);
		deleteFile(fileIdList);

		for (AttachedFile file : fileList) {
			java.io.File sysFile = new java.io.File(file.getPath());
			sysFile.delete();
		}
	}
	
	private void deleteRelation(List<Integer> fileIdList) throws TorqueException {
		Criteria criteria = new Criteria();
		criteria.addIn(TaskFileRelationPeer.FILE_ID, fileIdList);
		TaskFileRelationPeer.doDelete(criteria, con);
	}
	private void deleteFile(List<Integer> fileIdList) throws TorqueException {
		Criteria criteria = new Criteria();
		criteria.addIn(FilePeer.FILE_ID, fileIdList);
		FilePeer.doDelete(criteria, con);
	}
	
	protected File getDBModel(int fileId) throws NotFoundException, TorqueException, TorqueException {
		try {
			return FilePeer.retrieveByPK(fileId, con);
		} catch (NoRowsException e) {
			throw new NotFoundException("指定のファイル("+fileId+")");
		}
	}
}
