<%#
 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.ViewPermission;
import <%= packageName %>.domain.enumeration.ViewPermissionType;
import <%= packageName %>.domain.enumeration.TargetType;

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.IOException;
import java.io.InputStreamReader;
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;
import org.supercsv.cellprocessor.StrReplace;
import org.apache.commons.lang3.StringUtils;

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

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

    private  static List<ViewPermission> viewPermissions() {
        List<ViewPermission> result = new ArrayList<>();
        final CellProcessor[] processors = new CellProcessor[] {
                new ParseLong(),              // id
                new Optional(),               // name
                new Optional(),               // entityName
                new Optional(),               // tableName
                new Optional(),               // clazzName
                new Optional(),               // system
                new StrNULLTonull(new Optional(new ParseEnum(TargetType.class))), // targetType
                new Optional(),
                new Optional(),
                new Optional(),
                new Optional(),                // description
                new Optional(),                // creator.id
                new Optional(),                // businessType.id
                new Optional(),                // treeTable
                new Optional(),                // editInModal
                new Optional(),                // editInModal
                new StrNULLTonull(new Optional(new ParseEnum(ViewPermissionType.class))), // viewPermissionType
                new Optional(),                //
                new Optional(),                //
                new Optional(new StrReplace("NULL", "")),                //
                new Optional(),                //
                new Optional(),                //
        };
        final String[] FIELD_MAPPING = new String[]{
                "id",
                "text",
                "i18n",
                "group",
                "link",
                "externalLink",
                "target",
                "icon",
                "disabled",
                "hide",
                "hideInBreadcrumb",
                "shortcut",
                "shortcutRoot",
                "reuse",
                "code",
                "description",
                "type",
                "order",
                "apiPermissionCodes",
                "parent.id",
                "componentFile",
                "redirect"
        };

        ICsvDozerBeanReader beanReader = null;
        try {
            InputStream csvIn = InitialSetupMigration.class.getClassLoader().getResourceAsStream("config/liquibase/data/view_permission.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(ViewPermission.class, FIELD_MAPPING);

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

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if( beanReader != null ) {
                try {
                    beanReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        result.forEach(viewPermission -> {
            if (viewPermission.getParent() != null && StringUtils.isBlank(viewPermission.getParent().getId())) {
                viewPermission.setParent(null);
            }
        });
        return result;
    }

}
