/*************************************************************************
 *
 * Copyright 2009 by bBreak Systems.
 *
 * ExCella Reports - Excelファイルを利用した帳票ツール
 *
 * $Id: ColRepeatParamParserTest.java 33 2009-09-29 03:23:21Z tsuchida $
 * $Revision: 33 $
 *
 * This file is part of ExCella Reports.
 *
 * ExCella Reports is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * ExCella Reports 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 Lesser General Public License version 3 for more details
 * (a copy is included in the COPYING.LESSER file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with ExCella Reports.  If not, see
 * <http://www.gnu.org/licenses/lgpl-3.0-standalone.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
package org.bbreak.excella.reports.tag;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.bbreak.excella.core.exception.ParseException;
import org.bbreak.excella.core.util.PoiUtil;
import org.bbreak.excella.reports.ReportsTestUtil;
import org.bbreak.excella.reports.model.ConvertConfiguration;
import org.bbreak.excella.reports.model.ParamInfo;
import org.bbreak.excella.reports.model.ParsedReportInfo;
import org.bbreak.excella.reports.model.ReportBook;
import org.bbreak.excella.reports.model.ReportSheet;
import org.bbreak.excella.reports.processor.CellObject;
import org.bbreak.excella.reports.processor.ReportCreateHelper;
import org.bbreak.excella.reports.processor.ReportsCheckException;
import org.bbreak.excella.reports.processor.ReportsParserInfo;
import org.bbreak.excella.reports.processor.ReportsWorkbookTest;
import org.junit.Test;

/**
 * {@link org.bbreak.excella.reports.tag.ColRepeatParamParser} のためのテスト・クラス。
 * 
 * @since 1.0
 */
public class ColRepeatParamParserTest extends ReportsWorkbookTest {

    public ColRepeatParamParserTest( String version) {
        super( version);
    }

    /**
     * {@link org.bbreak.excella.reports.tag.ColRepeatParamParser#parse(org.apache.poi.ss.usermodel.Sheet, org.apache.poi.ss.usermodel.Cell, java.lang.Object)} のためのテスト・メソッド。
     */
    @Test
    public void testParseSheetCellObject() {
        Workbook workbook = null;
        // -----------------------
        // □[正常系]オプション指定なし
        // -----------------------
        workbook = getWorkbook();
        Sheet sheet1 = workbook.getSheetAt( 0);

        ReportBook reportBook = new ReportBook("",  "test", new ConvertConfiguration[] {});
        ReportSheet reportSheet1 = new ReportSheet( "sheet1", "Sheet1");
        reportBook.addReportSheet( reportSheet1);
        ReportSheet reportSheet2 = new ReportSheet( "sheet1", "Sheet2");
        reportBook.addReportSheet( reportSheet2);
        ReportSheet reportSheet3 = new ReportSheet( "sheet1", "Sheet3");
        reportBook.addReportSheet( reportSheet3);

        ReportSheet[] reportSheets = new ReportSheet[] {reportSheet1, reportSheet2, reportSheet3};

        for ( ReportSheet reportSheet : reportSheets) {
            ParamInfo info = reportSheet.getParamInfo();
            info.addParam( "$C[]", "A", new Object[] {"AA1", "AA1", "AA2", "AA2", "AA3"});
            info.addParam( "$C[]", "B", new Object[] {"BB1", "BB1", "BB2"});
            info.addParam( "$C[]", "C", new Object[] {"CC1", "CC2", "CC3", "CC4", "CC5"});
            info.addParam( "$", "D", "DDD");
        }

        ColRepeatParamParser parser = new ColRepeatParamParser();
        ReportsParserInfo reportsParserInfo = new ReportsParserInfo();
        reportsParserInfo.setReportParsers( new ArrayList<ReportsTagParser<?>>( ReportCreateHelper.createDefaultParsers().values()));
        reportsParserInfo.setReportBook( reportBook);
        reportsParserInfo.setParamInfo( reportSheets[0].getParamInfo());

        // 解析処理
        List<ParsedReportInfo> results = null;
        try {
            results = parseSheet( parser, sheet1, reportsParserInfo);
        } catch ( ParseException e) {
            fail( e.toString());
        }

        CellObject[] expectBeCells = new CellObject[] {new CellObject( 0, 0), new CellObject( 2, 1)};
        CellObject[] expectAfCells = new CellObject[] {new CellObject( 0, 4), new CellObject( 2, 3)};
        checkResult( expectBeCells, expectAfCells, results);

        // 不要シートを削除
        if ( version.equals( "2007")) {
            int index = workbook.getSheetIndex( PoiUtil.TMP_SHEET_NAME);
            if ( index > 0) {
                workbook.removeSheetAt( index);
            }
        }

        checkSheet( "Sheet1", sheet1, true);
        // -----------------------
        // □[正常系]オプション指定
        // ・重複非表示
        // ・上限回数
        // -----------------------
        workbook = getWorkbook();
        Sheet sheet2 = workbook.getSheetAt( 1);
        // 解析処理
        try {
            results = parseSheet( parser, sheet2, reportsParserInfo);
        } catch ( ParseException e) {
            fail( e.toString());
        }

        expectBeCells = new CellObject[] {new CellObject( 0, 0), new CellObject( 2, 1), new CellObject( 4, 2)};
        expectAfCells = new CellObject[] {new CellObject( 0, 4), new CellObject( 2, 3), new CellObject( 4, 3)};
        checkResult( expectBeCells, expectAfCells, results);

        // 不要シートを削除
        if ( version.equals( "2007")) {
            int index = workbook.getSheetIndex( PoiUtil.TMP_SHEET_NAME);
            if ( index > 0) {
                workbook.removeSheetAt( index);
            }
        }
        checkSheet( "Sheet2", sheet2, true);

        // -----------------------
        // □[正常系]オプション指定
        // ・シートリンク
        // -----------------------
        workbook = getWorkbook();
        Sheet sheet3 = workbook.getSheetAt( 2);
        // 解析処理
        try {
            results = parseSheet( parser, sheet3, reportsParserInfo);
        } catch ( ParseException e) {
            e.printStackTrace();
            fail( e.toString());
        }

        expectBeCells = new CellObject[] {new CellObject( 0, 0), new CellObject( 1, 0), new CellObject( 2, 0), new CellObject( 16, 0), new CellObject( 17, 0)};
        expectAfCells = new CellObject[] {new CellObject( 0, 2), new CellObject( 1, 1), new CellObject( 2, 4), new CellObject( 16, 2), new CellObject( 17, 2)};
        checkResult( expectBeCells, expectAfCells, results);

        // 不要シートを削除
        if ( version.equals( "2007")) {
            int index = workbook.getSheetIndex( PoiUtil.TMP_SHEET_NAME);
            if ( index > 0) {
                workbook.removeSheetAt( index);
            }
        }
        checkSheet( "Sheet3", sheet3, true);

        // -----------------------
        // □[異常系]チェック
        // ・必須パラメータなし：置換変数
        // ・シートハイパーリンク設定有無と重複非表示は重複不可
        // -----------------------
        workbook = getWorkbook();
        Sheet sheet4 = workbook.getSheetAt( 3);
        // 解析処理
        try {
            results = parseSheet( parser, sheet4, reportsParserInfo);
        } catch ( ParseException e) {
            fail( e.toString());
        }

        expectBeCells = new CellObject[] {new CellObject( 0, 0), new CellObject( 1, 0), new CellObject( 2, 0)};
        expectAfCells = new CellObject[] {new CellObject( 0, 0), new CellObject( 1, 0), new CellObject( 2, 0)};
        checkResult( expectBeCells, expectAfCells, results);

        // 不要シートを削除
        if ( version.equals( "2007")) {
            int index = workbook.getSheetIndex( PoiUtil.TMP_SHEET_NAME);
            if ( index > 0) {
                workbook.removeSheetAt( index);
            }
        }
        checkSheet( "Sheet4", sheet4, true);

        Sheet sheet5 = workbook.getSheetAt( 4);
        // 解析処理
        try {
            results = parseSheet( parser, sheet5, reportsParserInfo);
            fail( "シートハイパーリンク設定有無と重複非表示は重複不可チェックにかかっていない");
        } catch ( ParseException e) {
        }

        // -----------------------
        // ■[異常系]チェック
        // ・エラーがあった場合
        // -----------------------
        workbook = getWorkbook();
        Sheet sheet6 = workbook.getSheetAt( 5);
        // 解析処理
        try {
            results = parseSheet( parser, sheet6, reportsParserInfo);
            fail();
        } catch ( ParseException e) {
            assertTrue( e instanceof ParseException);
        }

    }

    /**
     * {@link org.bbreak.excella.reports.tag.ColRepeatParamParser#useControlRow()} のためのテスト・メソッド。
     */
    @Test
    public void testUseControlRow() {
        // -----------------------
        // □制御行使用有無：無
        // -----------------------
        ColRepeatParamParser parser = new ColRepeatParamParser();
        assertFalse( parser.useControlRow());
    }

    /**
     * {@link org.bbreak.excella.reports.tag.ColRepeatParamParser#ColRepeatParamParser(java.lang.String)} のためのテスト・メソッド。
     */
    @Test
    public void testColRepeatParamParserString() {

        ColRepeatParamParser parser = new ColRepeatParamParser( "てすと");

        assertEquals( "てすと", parser.getTag());
    }

    private void checkSheet( String expectedSheetName, Sheet actualSheet, boolean outputExcel) {

        // 期待値ブックの読み込み
        Workbook expectedWorkbook = getExpectedWorkbook();
        Sheet expectedSheet = expectedWorkbook.getSheet( expectedSheetName);

        try {
            // チェック
            ReportsTestUtil.checkSheet( expectedSheet, actualSheet, false);
        } catch ( ReportsCheckException e) {
            fail( e.getCheckMessagesToString());
        } finally {
            String tmpDirPath = ReportsTestUtil.getTestOutputDir();
            try {
                String filepath = null;
                Date now = new Date();
                if ( version.equals( "2007")) {
                    filepath = tmpDirPath + this.getClass().getSimpleName() + now.getTime() + ".xlsx";
                } else {
                    filepath = tmpDirPath + this.getClass().getSimpleName() + now.getTime() + ".xls";
                }
                PoiUtil.writeBook( actualSheet.getWorkbook(), filepath);

            } catch ( IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void checkResult( CellObject[] exceptedBeforeCells, CellObject[] exceptedAfterCells, List<ParsedReportInfo> results) {
        // 処理結果のチェック
        assertEquals( exceptedAfterCells.length, results.size());

        CellObject[] actualBreforeCells = new CellObject[results.size()];
        CellObject[] actualAfterCells = new CellObject[results.size()];

        for ( int i = 0; i < results.size(); i++) {
            ParsedReportInfo parsedReportInfo = results.get( i);
            // 処理前値のチェック
            actualBreforeCells[i] = new CellObject( parsedReportInfo.getDefaultRowIndex(), parsedReportInfo.getDefaultColumnIndex());
            actualAfterCells[i] = new CellObject( parsedReportInfo.getRowIndex(), parsedReportInfo.getColumnIndex());
        }
        // 処理後値のチェック
        assertArrayEquals( exceptedBeforeCells, actualBreforeCells);
        assertArrayEquals( exceptedAfterCells, actualAfterCells);

    }

}
