/*
 * Copyright 2002-2024 the original author or authors.
 *
 * 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 org.springframework.batch.extensions.bigquery.writer;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.cloud.bigquery.Table;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;

/**
 * JSON writer for BigQuery.
 *
 * @param <T> your DTO type
 * @author Volodymyr Perebykivskyi
 * @since 0.2.0
 * @see <a href="https://en.wikipedia.org/wiki/JSON">JSON</a>
 */
public class BigQueryJsonItemWriter<T> extends BigQueryBaseItemWriter<T> implements InitializingBean {

    private Converter<T, byte[]> rowMapper;
    private ObjectWriter objectWriter;
    private Class<?> itemClass;

    @Override
    protected void doInitializeProperties(List<? extends T> items) {
        if (this.itemClass == null) {
            T firstItem = items.stream().findFirst().orElseThrow(() -> {
                logger.warn("Class type was not found");
                return new IllegalStateException("Class type was not found");
            });
            this.itemClass = firstItem.getClass();

            if (this.rowMapper == null) {
                this.objectWriter = new ObjectMapper().writerFor(this.itemClass);
            }

            logger.debug("Writer setup is completed");
        }
    }

    /**
     * Converter that transforms a single row into a byte array.
     *
     * @param rowMapper your JSON row mapper
     */
    public void setRowMapper(Converter<T, byte[]> rowMapper) {
        this.rowMapper = rowMapper;
    }

    @Override
    protected List<byte[]> convertObjectsToByteArrays(List<? extends T> items) {
        return items
                .stream()
                .map(this::mapItemToJson)
                .filter(ArrayUtils::isNotEmpty)
                .map(String::new)
                .map(this::convertToNdJson)
                .filter(Predicate.not(ObjectUtils::isEmpty))
                .map(row -> row.getBytes(StandardCharsets.UTF_8))
                .toList();
    }

    @Override
    public void afterPropertiesSet() {
        super.baseAfterPropertiesSet(() -> {
            Table table = getTable();

            if (Boolean.TRUE.equals(writeChannelConfig.getAutodetect())) {
                if (tableHasDefinedSchema(table) && super.logger.isWarnEnabled()) {
                    logger.warn("Mixing autodetect mode with already defined schema may lead to errors on BigQuery side");
                }
            } else {
                Assert.notNull(writeChannelConfig.getSchema(), "Schema must be provided");

                if (tableHasDefinedSchema(table)) {
                    Assert.isTrue(
                            Objects.equals(table.getDefinition().getSchema(), writeChannelConfig.getSchema()),
                            "Schema should be the same"
                    );
                }
            }

            return null;
        });
    }

    private byte[] mapItemToJson(T t) {
        try {
            return Objects.isNull(rowMapper) ? objectWriter.writeValueAsBytes(t) : rowMapper.convert(t);
        }
        catch (JsonProcessingException e) {
            logger.error("Error during processing of the line: ", e);
            return null;
        }
    }

    /**
     * BigQuery uses <a href="https://github.com/ndjson/ndjson-spec">ndjson</a>.
     * It is expected that to pass here JSON line generated by
     * {@link com.fasterxml.jackson.databind.ObjectMapper} or any other JSON parser.
     */
    private String convertToNdJson(String json) {
        return json.concat(org.apache.commons.lang3.StringUtils.LF);
    }

}