/*******************************************************************************
 * 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.xliff.util.task;

import java.io.File;
import java.io.IOException;

import blanco.xliff.BlancoXliffParser;
import blanco.xliff.BlancoXliffUtil;
import blanco.xliff.util.task.valueobject.BlancoXliffUtilSplitProcessInput;
import blanco.xliff.valueobject.BlancoXliff;
import blanco.xliff.valueobject.BlancoXliffFile;
import blanco.xliff.valueobject.BlancoXliffTransUnit;

public class BlancoXliffUtilSplitProcessImpl implements
        BlancoXliffUtilSplitProcess {

    private BlancoXliffUtilSplitProcessInput fInput = null;

    private BlancoXliff fXliffSource = new BlancoXliff();

    private BlancoXliff fXliffTarget = new BlancoXliff();

    private int fProcessedFileCount = 0;

    private int fProcessedTransUnitCount = 0;

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

        final File fileXliff = new File(input.getSourcefile());
        final File targetDir = new File(input.getTargetdir());

        if (fileXliff.exists() == false) {
            throw new IllegalArgumentException("指定された sourcefile["
                    + fileXliff.getAbsolutePath() + "]は存在しません。");
        }
        if (fileXliff.canRead() == false) {
            throw new IllegalArgumentException("指定された sourcefile["
                    + fileXliff.getAbsolutePath() + "]は読み込むことが出来ません。");
        }

        if (targetDir.exists() == false) {
            if (targetDir.mkdirs() == false) {
                throw new IllegalArgumentException("指定された targetdir["
                        + targetDir.getAbsolutePath()
                        + "]が存在しなかったので作成しようとしましたが失敗しました。");
            }
        }
        if (targetDir.isDirectory() == false) {
            throw new IllegalArgumentException("指定された targetdir["
                    + targetDir.getAbsolutePath() + "]はディレクトリではありません。");
        }

        process(fileXliff, targetDir);

        return 0;
    }

    private void process(final File fileXliff, final File targetDir)
            throws IOException {

        // 読み込む。
        fXliffSource = new BlancoXliffParser().parse(fileXliff);

        // 書き出す
        for (int indexFile = 0; indexFile < fXliffSource.getFileList().size(); indexFile++) {
            final BlancoXliffFile file = fXliffSource.getFileList().get(
                    indexFile);
            processFile(file);
        }

        // 未保存で残っているものがあれば これを保存。
        if (fProcessedTransUnitCount > 0) {
            fProcessedTransUnitCount = 0;
            save();
        }
    }

    private void processFile(final BlancoXliffFile file) throws IOException {
        {
            final BlancoXliffFile xliffFile = new BlancoXliffFile();
            fXliffTarget.getFileList().add(xliffFile);
        }

        for (int index = 0; index < file.getBody().getTransUnitList().size(); index++) {
            final BlancoXliffTransUnit transUnit = file.getBody()
                    .getTransUnitList().get(index);

            processTransUnit(transUnit);

            fProcessedTransUnitCount++;

            if (fProcessedTransUnitCount >= fInput.getCount()) {
                // 書き出し。
                fProcessedTransUnitCount = 0;
                save();
            }
        }
    }

    private void processTransUnit(final BlancoXliffTransUnit transUnit) {

        final BlancoXliffFile xliffFile = fXliffTarget.getFileList().get(
                fXliffTarget.getFileList().size() - 1);
        xliffFile.getBody().getTransUnitList().add(transUnit);
    }

    private void save() throws IOException {

        fProcessedFileCount++;
        final File fileTargetfile = new File(fInput.getTargetdir() + "/"
                + new File(fInput.getSourcefile()).getName() + "-"
                + fProcessedFileCount + ".xlf");

        final String symbolicName = new File(fInput.getSourcefile()).getName()
                .substring(
                        0,
                        new File(fInput.getSourcefile()).getName().length()
                                - ".xlf".length());

        BlancoXliffUtil.saveXliffInstance(fXliffTarget, new File(fileTargetfile
                .getParentFile().getAbsolutePath()), symbolicName + "-"
                + fProcessedFileCount);

        System.out.println("xliff: split: create: " + symbolicName + "-"
                + fProcessedFileCount);

        fXliffTarget = new BlancoXliff();
        final BlancoXliffFile xliffFile = new BlancoXliffFile();
        fXliffTarget.getFileList().add(xliffFile);
    }
}
