/*******************************************************************************
 * Copyright (c) 2008 IGA Tosiki, NTT DATA BUSINESS BRAINS Corp.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    IGA Tosiki (NTT DATA BUSINESS BRAINS Corp.) - initial API and implementation
 *******************************************************************************/
/*
 * blanco Framework
 * Copyright (C) 2008 NTT DATA BUSINESS BRAINS CORPORATION
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 */
package blanco.pleiades.util.task;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;

import blanco.pleiades.util.task.valueobject.BlancoPleiadesUtilPleiades2TmxProcessInput;
import blanco.tmx.BlancoTmxSerializer;
import blanco.tmx.valueobject.BlancoTmx;
import blanco.tmx.valueobject.BlancoTmxTu;
import blanco.tmx.valueobject.BlancoTmxTuv;

public class BlancoPleiadesUtilPleiades2TmxProcessImpl implements
        BlancoPleiadesUtilPleiades2TmxProcess {
    private BlancoPleiadesUtilPleiades2TmxProcessInput fInput = null;

    private Map<String, String> fProcessedMap = new HashMap<String, String>();

    public int execute(final BlancoPleiadesUtilPleiades2TmxProcessInput input)
            throws IOException, IllegalArgumentException {
        fInput = input;

        final File sourceFile = new File(fInput.getSourcefile());
        if (sourceFile.exists() == false) {
            throw new IllegalArgumentException("指定された sourcefile["
                    + sourceFile.getAbsolutePath() + "]は存在しません。");
        }
        if (sourceFile.isFile() == false) {
            throw new IllegalArgumentException("指定された sourcefile["
                    + sourceFile.getAbsolutePath() + "]はファイルではありません。");
        }

        final File targetFile = new File(fInput.getTargetfile());
        if (targetFile.exists()) {
            if (targetFile.delete() == false)
                throw new IllegalArgumentException("指定された targetfile["
                        + targetFile.getAbsolutePath()
                        + "]が存在したので削除を試みましたが失敗しました。");
        }

        if (sourceFile.getCanonicalPath().equals(targetFile.getCanonicalPath())) {
            throw new IllegalArgumentException("sourcefile["
                    + sourceFile.getAbsolutePath() + "] と targetfile["
                    + targetFile.getAbsolutePath() + "] とは同じファイルです。");
        }

        if (targetFile.getParentFile().exists() == false) {
            if (targetFile.getParentFile().mkdirs() == false) {
                throw new IllegalArgumentException("指定された targetfile["
                        + targetFile.getAbsolutePath()
                        + "]を格納するためのディレクトリ作成を試みましたが失敗しました。");
            }
        }

        process(sourceFile, targetFile);

        return 0;
    }

    @SuppressWarnings("unchecked")
    private void process(final File fileSource, final File fileTarget)
            throws IOException {
        final BlancoTmx tmx = new BlancoTmx();

        final Iterator ite = readProperties(fileSource).entrySet().iterator();
        for (; ite.hasNext();) {
            final Entry entry = (Entry) ite.next();

            if (fProcessedMap.get(entry.getKey().toString()) != null) {
                // 既に処理済みの文字列については処理対象外とします。
                System.out.println("trace: すでに処理済み:["
                        + entry.getKey().toString() + "]");
                continue;
            } else {
                fProcessedMap.put(entry.getKey().toString(), entry.getValue()
                        .toString());
            }

            final BlancoTmxTu tu = new BlancoTmxTu();
            tmx.getBody().getTuList().add(tu);
            {
                final BlancoTmxTuv tuv = new BlancoTmxTuv();
                tu.getTuvList().add(tuv);
                tuv.setLang("EN-US");
                tuv.setSeg(entry.getKey().toString());
            }
            {
                final BlancoTmxTuv tuv = new BlancoTmxTuv();
                tu.getTuvList().add(tuv);
                tuv.setLang("JA");
                tuv.setSeg(entry.getValue().toString());
            }
        }

        // abc 順で並べ替えます。
        Collections.sort(tmx.getBody().getTuList(),
                new java.util.Comparator<BlancoTmxTu>() {
                    public int compare(final BlancoTmxTu obj1,
                            final BlancoTmxTu obj2) {
                        final BlancoTmxTu tu1 = obj1;
                        final BlancoTmxTu tu2 = obj2;
                        return tu1.getTuvList().get(0).getSeg().compareTo(
                                tu2.getTuvList().get(0).getSeg());
                    }
                });

        final BlancoTmxSerializer serializer = new BlancoTmxSerializer();
        serializer.serialize(tmx, fileTarget);
    }

    private Properties readProperties(final File fileSource) throws IOException {
        final Properties props = new Properties();
        props.load(new BufferedInputStream(new FileInputStream(fileSource)));
        return props;
    }
}
