/*
 * Copyright 2016-2018 shardingsphere.io.
 * <p>
 * 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.
 * </p>
 */

package io.shardingsphere.core.executor.sql.execute.result;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import io.shardingsphere.core.merger.QueryResult;
import lombok.SneakyThrows;

import java.io.InputStream;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * Distinct query result.
 *
 * @author panjuan
 */
public final class DistinctQueryResult implements QueryResult {
    
    private final Multimap<String, Integer> columnLabelAndIndexMap;
    
    private final Iterator<List<Object>> resultData;
    
    private List<Object> currentRow;
    
    @SneakyThrows
    public DistinctQueryResult(final Collection<QueryResult> queryResults) {
        this.columnLabelAndIndexMap = getColumnLabelAndIndexMap(queryResults.iterator().next());
        resultData = getResultData(queryResults);
    }
    
    @SneakyThrows
    private Multimap<String, Integer> getColumnLabelAndIndexMap(final QueryResult queryResult) {
        Multimap<String, Integer> result = HashMultimap.create();
        for (int columnIndex = 1; columnIndex <= queryResult.getColumnCount(); columnIndex++) {
            result.put(queryResult.getColumnLabel(columnIndex), columnIndex);
        }
        return result;
    }
    
    @SneakyThrows
    private Iterator<List<Object>> getResultData(final Collection<QueryResult> queryResults) {
        Set<List<Object>> result = new LinkedHashSet<>();
        for (QueryResult each : queryResults) {
            while (each.next()) {
                List<Object> row = new ArrayList<>(each.getColumnCount());
                for (int columnIndex = 1; columnIndex <= each.getColumnCount(); columnIndex++) {
                    row.add(each.getValue(columnIndex, Object.class));
                }
                result.add(row);
            }
        }
        return result.iterator();
    }
    
    @SneakyThrows
    private Map<Integer, Set<Object>> getColumnIndexAndDistinctValues(final Collection<QueryResult> queryResults) {
        Map<Integer, Set<Object>> result = createColumnIndexAndDistinctValues(queryResults);
        for (QueryResult each : queryResults) {
            fillInColumnIndexAndDistinctValues(result, each);
        }
        return result;
    }
    
    private Map<Integer, Set<Object>> createColumnIndexAndDistinctValues(final Collection<QueryResult> queryResults) throws SQLException {
        Map<Integer, Set<Object>> result = new LinkedHashMap<>(queryResults.iterator().next().getColumnCount());
        for (int i = 1; i <= queryResults.iterator().next().getColumnCount(); i++) {
            result.put(i, new LinkedHashSet<>());
        }
        return result;
    }
    
    @SneakyThrows
    private void fillInColumnIndexAndDistinctValues(final Map<Integer, Set<Object>> columnIndexAndDistinctValues, final QueryResult queryResult) {
        while (queryResult.next()) {
            for (int i = 1; i <= columnIndexAndDistinctValues.size(); i++) {
                columnIndexAndDistinctValues.get(i).add(queryResult.getValue(i, Object.class));
            }
        }
    }
    
    @Override
    public boolean next() {
        if (resultData.hasNext()) {
            currentRow = resultData.next();
            return true;
        }
        currentRow = null;
        return false;
    }

    @Override
    public Object getValue(final int columnIndex, final Class<?> type) {
        return currentRow.get(columnIndex - 1);
    }

    @Override
    public Object getValue(final String columnLabel, final Class<?> type) {
        return currentRow.get(getIndexByColumnLabel(columnLabel));
    }

    @Override
    public Object getCalendarValue(final int columnIndex, final Class<?> type, final Calendar calendar) {
        return currentRow.get(columnIndex - 1);
    }

    @Override
    public Object getCalendarValue(final String columnLabel, final Class<?> type, final Calendar calendar) {
        return currentRow.get(getIndexByColumnLabel(columnLabel));
    }

    @Override
    public InputStream getInputStream(final int columnIndex, final String type) {
        return (InputStream) currentRow.get(columnIndex - 1);
    }

    @Override
    public InputStream getInputStream(final String columnLabel, final String type) {
        return (InputStream) currentRow.get(getIndexByColumnLabel(columnLabel));
    }

    @Override
    public boolean wasNull() {
        return null == currentRow;
    }

    @Override
    public int getColumnCount() {
        return columnLabelAndIndexMap.size();
    }

    @Override
    public String getColumnLabel(final int columnIndex) throws SQLException {
        for (Entry<String, Integer> entry : columnLabelAndIndexMap.entries()) {
            if (columnIndex == entry.getValue()) {
                return entry.getKey();
            }
        }
        throw new SQLException("Column index out of range", "9999");
    }
}

@@ -2392,936 +2392,252 @@
     
-while (each.next()) %7B%0A                List%3CObject%3E row = new ArrayList%3C%3E(each.getColumnCount());%0A                for (int columnIndex = 1; columnIndex %3C= each.getColumnCount(); columnIndex++) %7B%0A                    row.add(each.getValue(columnIndex, Object.class));%0A                %7D%0A                result.add(row);%0A            %7D%0A        %7D%0A        return result.iterator();%0A    %7D%0A    %0A    @SneakyThrows%0A    private Map%3CInteger, Set%3CObject%3E%3E getColumnIndexAndDistinctValues(final Collection%3CQueryResult%3E queryResults) %7B%0A        Map%3CInteger, Set%3CObject%3E%3E result = createColumnIndexAndDistinctValues(queryResults);%0A        for (QueryResult each : queryResults) %7B%0A            fillInColumnIndexAndDistinctValues(result, each);%0A        %7D%0A        return result;
+fillInResultData(result, each);%0A        %7D%0A        return result.iterator();%0A    %7D%0A    %0A    private void fillInResultData(final Set%3CList%3CObject%3E%3E result, final QueryResult each) throws SQLException %7B
 %0A    
-%7D%0A
     
-%0A    private Map%3CInteger, Set%3CObject%3E%3E createColumnIndexAndDistinctValues(final Collection%3CQueryResult%3E queryResults) throws SQLException %7B%0A        Map%3CInteger, Se
+while (each.next()) %7B%0A            Lis
 t%3COb
@@ -2645,69 +2645,35 @@
 ect%3E
-%3E
  r
-esult
+ow
  = new 
-LinkedHashMap%3C%3E(queryResults.iterator().next()
+ArrayList%3C%3E(each
 .get
@@ -2688,32 +2688,36 @@
 unt());%0A        
+    
 for (int i = 1; 
@@ -2713,558 +2713,189 @@
 int 
-i = 1; i %3C= queryResults.iterator().next().getColumnCount(); i++) %7B%0A            result.put(i, new LinkedHashSet%3C%3E());%0A        %7D%0A        return result;%0A
+columnIndex = 1; columnIndex %3C= each.getColumnCount(); columnIndex++) %7B%0A         
     
-%7D%0A
    
- %0A    @SneakyThrows%0A    private void fillInColumnIndexAndDistinctValues(final Map%3CInteger, Set%3CObject%3E%3E columnIndexAndDistinctValues, final QueryResult queryResult) %7B%0A        while (queryResult.next()) %7B%0A            for (int i = 1; i %3C= columnIndexAndDistinctValues.size(); i++) %7B%0A                columnIndexAndDistinctValues.get(i).add(queryResult.getValue(i, Object.class));%0A            %7D
+row.add(each.getValue(columnIndex, Object.class));%0A            %7D%0A            result.add(row);
 %0A   

add fillInResultData()