/*
 * Copyright 2006-2011 the Seasar Foundation and the Others.
 *
 * 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 org.seasar.codegen.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.seasar.codegen.exception.FileNotFoundRuntimeException;
import org.seasar.codegen.exception.UnsupportedEncodingRuntimeException;
import org.seasar.framework.exception.IORuntimeException;

import au.com.bytecode.opencsv.CSVReader;

@SuppressWarnings("unchecked")
public class CSVToArrayUtil {
    public static List readCSVToArray(File srcFile, String encode) {
        BufferedReader bufferedreader = getBufferedReader(srcFile, encode);
        readLine(bufferedreader); // ヘッダ分読み飛ばし用

        CSVReader reader = new CSVReader(bufferedreader);
        try {
            return reader.readAll();
        } catch (IOException e) {
            throw new IORuntimeException(e);
        }
    }

    private static BufferedReader getBufferedReader(File srcFile, String encode) {
        InputStreamReader inputReader = null;
        try {
            String srcFileName = srcFile.getPath();
            FileInputStream fis = new FileInputStream(srcFileName);
            inputReader = new InputStreamReader(fis, encode);
        } catch (FileNotFoundException e) {
            throw new FileNotFoundRuntimeException(srcFile, e);
        } catch (UnsupportedEncodingException e) {
            throw new UnsupportedEncodingRuntimeException(srcFile, e);
        }
        BufferedReader bufferedreader = new BufferedReader(inputReader);
        return bufferedreader;
    }

    private static String readLine(BufferedReader bufferedreader) {
        String buff;
        try {
            buff = bufferedreader.readLine();
        } catch (IOException e) {
            throw new IORuntimeException(e);
        }
        return buff;
    }

    public static String getStringFromListPos(List oneLine, int pos) {
        if (oneLine.size() <= pos) {
            return "";
        }
        return (String) oneLine.get(pos);
    }

}
