/*
 * 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.
 */
package com.facebook.presto.execution;

import com.facebook.presto.Session;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.metadata.QualifiedTableName;
import com.facebook.presto.metadata.ViewDefinition;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.sql.analyzer.Analysis;
import com.facebook.presto.sql.analyzer.Analyzer;
import com.facebook.presto.sql.analyzer.FeaturesConfig;
import com.facebook.presto.sql.analyzer.Field;
import com.facebook.presto.sql.analyzer.QueryExplainer;
import com.facebook.presto.sql.parser.ParsingException;
import com.facebook.presto.sql.parser.SqlParser;
import com.facebook.presto.sql.planner.optimizations.PlanOptimizer;
import com.facebook.presto.sql.tree.CreateView;
import com.facebook.presto.sql.tree.Query;
import com.facebook.presto.sql.tree.Statement;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import io.airlift.json.JsonCodec;

import javax.inject.Inject;

import java.util.List;

import static com.facebook.presto.metadata.MetadataUtil.createQualifiedTableName;
import static com.facebook.presto.metadata.ViewDefinition.ViewColumn;
import static com.facebook.presto.spi.StandardErrorCode.INTERNAL_ERROR;
import static com.facebook.presto.sql.SqlFormatter.formatSql;
import static com.google.common.base.Preconditions.checkNotNull;

public class CreateViewTask
        implements DataDefinitionTask<CreateView>
{
    private final JsonCodec<ViewDefinition> codec;
    private final SqlParser sqlParser;
    private final List<PlanOptimizer> planOptimizers;
    private final boolean experimentalSyntaxEnabled;
    private final boolean distributedIndexJoinsEnabled;
    private final boolean distributedJoinsEnabled;

    @Inject
    public CreateViewTask(JsonCodec<ViewDefinition> codec, SqlParser sqlParser, List<PlanOptimizer> planOptimizers, FeaturesConfig featuresConfig)
    {
        this.codec = checkNotNull(codec, "codec is null");
        this.sqlParser = checkNotNull(sqlParser, "sqlParser is null");
        this.planOptimizers = ImmutableList.copyOf(checkNotNull(planOptimizers, "planOptimizers is null"));
        checkNotNull(featuresConfig, "featuresConfig is null");
        this.experimentalSyntaxEnabled = featuresConfig.isExperimentalSyntaxEnabled();
        this.distributedIndexJoinsEnabled = featuresConfig.isDistributedIndexJoinsEnabled();
        this.distributedJoinsEnabled = featuresConfig.isDistributedJoinsEnabled();
    }

    @Override
    public void execute(CreateView statement, Session session, Metadata metadata)
    {
        QualifiedTableName name = createQualifiedTableName(session, statement.getName());

        String sql = getFormattedSql(statement);

        Analysis analysis = analyzeStatement(statement, session, metadata);
        Iterable<Field> fields = analysis.getOutputDescriptor().getVisibleFields();

        List<ViewColumn> columns = FluentIterable.from(fields).transform(fieldToColumn()).toList();

        String data = codec.toJson(new ViewDefinition(sql, session.getCatalog(), session.getSchema(), columns));

        metadata.createView(session, name, data, statement.isReplace());
    }

    public Analysis analyzeStatement(Statement statement, Session session, Metadata metadata)
    {
        QueryExplainer explainer = new QueryExplainer(session, planOptimizers, metadata, sqlParser, experimentalSyntaxEnabled, distributedIndexJoinsEnabled, distributedJoinsEnabled);
        Analyzer analyzer = new Analyzer(session, metadata, sqlParser, Optional.of(explainer), experimentalSyntaxEnabled);
        return analyzer.analyze(statement);
    }

    private static Function<Field, ViewColumn> fieldToColumn()
    {
        return new Function<Field, ViewColumn>()
        {
            @Override
            public ViewColumn apply(Field field)
            {
                return new ViewColumn(field.getName().get(), field.getType());
            }
        };
    }

    private String getFormattedSql(CreateView statement)
    {
        Query query = statement.getQuery();
        String sql = formatSql(query);

        // verify round-trip
        Statement parsed;
        try {
            parsed = sqlParser.createStatement(sql);
        }
        catch (ParsingException e) {
            throw new PrestoException(INTERNAL_ERROR, "Formatted query does not parse: " + query);
        }
        if (!query.equals(parsed)) {
            throw new PrestoException(INTERNAL_ERROR, "Query does not round-trip: " + query);
        }

        return sql;
    }
}

@@ -993,55 +993,8 @@
 ig;%0A
-import com.facebook.presto.sql.analyzer.Field;%0A
 impo
@@ -1390,105 +1390,16 @@
 ase.
-Function;%0Aimport com.google.common.base.Optional;%0Aimport com.google.common.collect.FluentIterable
+Optional
 ;%0Aim
@@ -1818,16 +1818,92 @@
 matSql;%0A
+import static com.facebook.presto.util.ImmutableCollectors.toImmutableList;%0A
 import s
@@ -3401,24 +3401,25 @@
 adata);%0A
+%0A
         
 Iterable
@@ -3414,29 +3414,31 @@
     
-Iterable%3CField%3E field
+List%3CViewColumn%3E column
 s = 
@@ -3467,16 +3467,33 @@
 riptor()
+%0A                
 .getVisi
@@ -3507,109 +3507,147 @@
 ds()
-;%0A%0A        List%3CViewColumn%3E columns = FluentIterable.from(fields).transform(fieldToColumn()).to
+.stream()%0A                .map(field -%3E new ViewColumn(field.getName().get(), field.getType()))%0A                .collect(toImmutable
 List()
+)
 ;%0A%0A 
@@ -4300,332 +4300,8 @@
  %7D%0A%0A
-    private static Function%3CField, ViewColumn%3E fieldToColumn()%0A    %7B%0A        return new Function%3CField, ViewColumn%3E()%0A        %7B%0A            @Override%0A            public ViewColumn apply(Field field)%0A            %7B%0A                return new ViewColumn(field.getName().get(), field.getType());%0A            %7D%0A        %7D;%0A    %7D%0A%0A
     

Remove constructor function from CreateViewTask