/*
 * Copyright 2018 Philipp Salvisberg <philipp.salvisberg@trivadis.com>
 * 
 * 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.utplsql.sqldev.oddgen;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import org.utplsql.sqldev.dal.UtplsqlDao;
import org.utplsql.sqldev.model.StringTools;
import org.utplsql.sqldev.model.oddgen.GenContext;

public class TestTemplate {
    private final GenContext context;
    private final List<String> units;
    private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private final String today = dateTimeFormatter.format(LocalDateTime.now());

    public TestTemplate(final GenContext context) {
        this.context = context;
        UtplsqlDao dao = new UtplsqlDao(context.getConn());
        units = dao.units(context.getObjectType(), context.getObjectName());
    }

    public String generateSpec() {
        final StringBuilder sb = new StringBuilder();
        final String objectName = context.getObjectName().toLowerCase();
        final String packageName = context.getTestPackagePrefix() + objectName + context.getTestPackageSuffix();
        sb.append("create or replace package ");
        sb.append(packageName);
        sb.append(" is\n\n");
        if (context.isGenerateComments()) {
            sb.append("\t-- generated by utPLSQL for SQL Developer on ");
            sb.append(today);
            sb.append("\n\n");
        }
        sb.append("\t--%suite(");
        sb.append(packageName);
        sb.append(")\n");
        if (!context.getSuitePath().isEmpty()) {
            sb.append("\t--%suitepath(");
            sb.append(context.getSuitePath());
            sb.append(")\n\n");
        }
        for (final String u : units) {
            final String unit = u.toLowerCase();
            if (context.getNumberOfTestsPerUnit() > 1
                    && ("PACKAGE".equals(context.getObjectType()) || "TYPE".equals(context.getObjectType()))) {
                sb.append("\t--%context(");
                sb.append(unit);
                sb.append(")\n\n");
            }
            for (int i=1; i <= context.getNumberOfTestsPerUnit(); i++) {
                sb.append("\t--%test\n");
                if (context.isDisableTests()) {
                    sb.append("\t--%disabled\n");
                }
                sb.append("\tprocedure ");
                sb.append(context.getTestUnitPrefix());
                sb.append(unit);
                sb.append(context.getTestUnitSuffix());
                if (context.getNumberOfTestsPerUnit() > 1) {
                    sb.append(i);
                }
                sb.append(";\n\n");
            }
            if (context.getNumberOfTestsPerUnit() > 1
                    && ("PACKAGE".equals(context.getObjectType()) || "TYPE".equals(context.getObjectType()))) {
                sb.append("\t--%endcontext\n\n");
            }
        }
        sb.append("end ");
        sb.append(packageName);
        sb.append(";\n");
        sb.append("/");
        final String ret = sb.toString();
        return StringTools.replaceTabsWithSpaces(ret, context.getIndentSpaces());
    }

    public String generateBody() {
        StringBuilder sb = new StringBuilder();
        final String objectName = context.getObjectName().toLowerCase();
        sb.append("create or replace package body ");
        sb.append(context.getTestPackagePrefix());
        sb.append(objectName);
        sb.append(context.getTestPackageSuffix());
        sb.append(" is\n\n");
        if (context.isGenerateComments()) {
            sb.append("\t-- generated by utPLSQL for SQL Developer on ");
            sb.append(today);
            sb.append("\n\n");
        }
        for (final String u : units) {
            final String unit = u.toLowerCase();
            for (int i=1; i <= context.getNumberOfTestsPerUnit(); i++) {
                final String procedureName = context.getTestUnitPrefix() + unit + context.getTestUnitSuffix()
                        + (context.getNumberOfTestsPerUnit() > 1 ? String.valueOf(i) : "");
                if (context.isGenerateComments()) {
                    sb.append("\t--\n");
                    sb.append("\t-- test ");
                    sb.append(unit);
                    if (context.getNumberOfTestsPerUnit() > 1) {
                        sb.append(" case ");
                        sb.append(i);
                        sb.append(": ...\n");
                    } else {
                        sb.append("\n");
                    }
                    sb.append("\t--\n");
                }
                sb.append("\tprocedure ");
                sb.append(procedureName);
                sb.append(" is\n");
                sb.append("\t\tl_actual   integer := 0;\n");
                sb.append("\t\tl_expected integer := 1;\n");
                sb.append("\tbegin\n");
                if (context.isGenerateComments()) {
                    sb.append("\t\t-- arrange\n\n");
                    sb.append("\t\t-- act\n");
                    sb.append("\t\t-- ");
                    sb.append(objectName);
                    sb.append(".");
                    sb.append(unit);
                    sb.append(";\n\n");
                    sb.append("\t\t-- assert\n");
                }
                sb.append("\t\tut.expect(l_actual).to_equal(l_expected);\n");
                sb.append("\tend ");
                sb.append(procedureName);
                sb.append(";\n\n");
            }
        }
        sb.append("end ");
        sb.append(context.getTestPackagePrefix());
        sb.append(objectName);
        sb.append(context.getTestPackageSuffix());
        sb.append(";\n");
        sb.append("/");
        final String ret = sb.toString();
        return StringTools.replaceTabsWithSpaces(ret, context.getIndentSpaces());
    }

    public CharSequence generate() {
        StringBuilder sb = new StringBuilder();
        sb.append(generateSpec());
        sb.append("\n\n");
        sb.append(generateBody());
        sb.append('\n');
        return sb;
    }
}
