<%#
 Copyright 2013-2021 the original author or authors from the BegCode project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 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

      https://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 <%= packageName %>.config.dbmigrations;

import <%= packageName %>.domain.CommonTableField;
import <%= packageName %>.domain.enumeration.CommonFieldType;
import <%= packageName %>.domain.enumeration.EndUsedType;

import com.github.cloudyrock.mongock.ChangeLog;
import com.github.cloudyrock.mongock.ChangeSet;
import com.github.cloudyrock.mongock.driver.mongodb.springdata.v3.decorator.impl.MongockTemplate;

import java.util.ArrayList;
import java.util.List;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.cellprocessor.Optional;
import org.supercsv.cellprocessor.ParseEnum;
import org.supercsv.cellprocessor.ParseLong;
import org.supercsv.io.dozer.ICsvDozerBeanReader;
import org.supercsv.io.dozer.CsvDozerBeanReader;
import org.supercsv.prefs.CsvPreference;

/**
 * Creates the initial database setup.
 */
@ChangeLog(order = "005")
public class InitialCommonTableFieldMigration {

    @ChangeSet(order = "01", author = "initiator", id = "01-addCommonTableFields")
    public void addCommonTableFields(MongockTemplate mongoTemplate) {
        mongoTemplate.insertAll(commonTableFields());
    }

    private  static List<CommonTableField> commonTableFields() {
        List<CommonTableField> result = new ArrayList<>();
        final CellProcessor[] processors = new CellProcessor[] {
                new ParseLong(),              // id
                new Optional(),               // title
                new Optional(),               // entityFieldName
                new StrNULLTonull(new Optional(new ParseEnum(CommonFieldType.class))), // type
                new Optional(),               // tableColumnName
                new Optional(),               // columnWidth
                new Optional(),               // hideInList
                new Optional(), // common_table_id
                new Optional(), // system
                new Optional(), // edit_in_list
                new Optional(),                // clientReadOnly
                new Optional(),                // fieldValues
                new Optional(),                // order
                new Optional(),                // notNull
                new Optional(),                // validateRules
                new Optional(),                // treeIndicator
                new StrNULLTonull(new Optional(new ParseEnum(EndUsedType.class))), // endUsed
                new Optional(),                // hideInForm
                new Optional(),                // sortable
                new Optional(),  // searchForm
        };
        final String[] FIELD_MAPPING = new String[]{
                "id",
                "title",
                "entityFieldName",
                "type",
                "tableColumnName",
                "columnWidth",
                "hideInList",
                "commonTable.id",
                "system",
                "editInList",
                "clientReadOnly",
                "fieldValues",
                "order",
                "notNull",
                "validateRules",
                "treeIndicator",
                "endUsed",
                "hideInForm",
                "sortable",
                "searchForm",
        };

        ICsvDozerBeanReader beanReader = null;
        try {
            InputStream csvIn = InitialSetupMigration.class.getClassLoader().getResourceAsStream("config/liquibase/data/common_table_field.csv");
            beanReader = new CsvDozerBeanReader(new InputStreamReader(csvIn, StandardCharsets.UTF_8), (new CsvPreference.Builder('"', 59, "\r\n")).build());
            beanReader.getHeader(true); // ignore the header
            beanReader.configureBeanMapping(CommonTableField.class, FIELD_MAPPING);

            CommonTableField commonTableField;
            while( (commonTableField = beanReader.read(CommonTableField.class, processors)) != null ) {
                result.add(commonTableField);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if( beanReader != null ) {
                try {
                    beanReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
