/*
 * Aipo is a groupware program developed by Aimluck,Inc.
 * http://aipostyle.com/
 *
 * Copyright(C) 2011 avanza Co.,Ltd. All rights reserved.
 * http://www.avnz.co.jp/
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package com.aimluck.eip.mail.util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.activation.DataSource;

import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;

/**
 * テキスト本文に含まれるIBM拡張文字補正 DataSource クラスです。 <br />
 * 
 */
public class SJISDataSource implements DataSource {

  private byte[] data;

  private String contentType;

  /** logger */
  private static final JetspeedLogger logger =
    JetspeedLogFactoryService.getLogger(SJISDataSource.class.getName());

  public SJISDataSource(InputStream s, String contentType) {
    // try {
    // byte型の配列を出力する
    setContentType(contentType);
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    OutputStream os = new BufferedOutputStream(b);
    int c;
    try {
      while ((c = s.read()) != -1) {
        os.write(c);
      }
    } catch (IOException e) {
      logger.error("メールテキスト本文をbyte型の配列への出力中にエラーが発生しました。", e);
    } finally {
      if (os != null) {
        try {
          os.flush();
          os.close();
        } catch (IOException e) {
          logger.error("メールテキスト本文をbyte型の配列への出力中にエラーが発生しました。", e);
        }
      }
    }
    // JISのバイト配列
    data = b.toByteArray();
    data = ALMailUtils.JIStoSJIS(data);

  }

  public String getContentType() {
    return contentType;
  }

  public InputStream getInputStream() throws IOException {
    if (data == null) {
      throw new IOException("no data");
    }
    return new ByteArrayInputStream(data);
  }

  public OutputStream getOutputStream() throws IOException {
    throw new IOException("cannot do this");
  }

  public String getName() {
    return "dummy";
  }

  public void setContentType(String s) {
    contentType = s;
  }
}
