/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.apache.shardingsphere.test.e2e.env.runtime.type.scenario.authority;

import com.google.common.base.Splitter;
import lombok.Setter;
import org.apache.shardingsphere.database.connector.core.type.DatabaseType;
import org.apache.shardingsphere.infra.spi.type.typed.TypedSPILoader;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Authority environment SQL set XML entry.
 */
@XmlAccessorType(XmlAccessType.FIELD)
@Setter
public final class AuthorityEnvironmentSQLSet {
    
    @XmlAttribute(name = "db-types", required = true)
    private String databaseTypes;
    
    @XmlElementWrapper(name = "init")
    @XmlElement(name = "sql")
    private List<String> initSQLs = new LinkedList<>();
    
    @XmlElementWrapper(name = "clean")
    @XmlElement(name = "sql")
    private List<String> cleanSQLs = new LinkedList<>();
    
    /**
     * Get all init SQLs.
     *
     * @param databaseType database type
     * @return init SQLs
     */
    public Collection<String> getInitSQLs(final DatabaseType databaseType) {
        return getDatabaseTypes().contains(databaseType) ? initSQLs : Collections.emptyList();
    }
    
    /**
     * Get all clean SQLs.
     *
     * @param databaseType database type
     * @return clean SQLs
     */
    public Collection<String> getCleanSQLs(final DatabaseType databaseType) {
        return getDatabaseTypes().contains(databaseType) ? cleanSQLs : Collections.emptyList();
    }
    
    private Collection<DatabaseType> getDatabaseTypes() {
        return Splitter.on(",").trimResults().splitToList(databaseTypes).stream().map(each -> TypedSPILoader.getService(DatabaseType.class, each)).collect(Collectors.toList());
    }
}
