/*
 * Copyright © 2021-present Arcade Data Ltd (info@arcadedata.com)
 *
 * 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.
 *
 * SPDX-FileCopyrightText: 2021-present Arcade Data Ltd (info@arcadedata.com)
 * SPDX-License-Identifier: Apache-2.0
 */
/* Generated By:JJTree: Do not edit this line. ArraySingleValuesSelector.java Version 4.3 */
/* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=true,NODE_PREFIX=O,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_USERTYPE_VISIBILITY_PUBLIC=true */
package com.arcadedb.query.sql.parser;

import com.arcadedb.database.Identifiable;
import com.arcadedb.exception.CommandExecutionException;
import com.arcadedb.query.sql.executor.CommandContext;
import com.arcadedb.query.sql.executor.MultiValue;
import com.arcadedb.query.sql.executor.Result;
import com.arcadedb.query.sql.executor.ResultInternal;

import java.util.*;
import java.util.stream.*;

public class ArraySingleValuesSelector extends SimpleNode {

  protected List<ArraySelector> items = new ArrayList<>();

  public ArraySingleValuesSelector(final int id) {
    super(id);
  }

  public void toString(final Map<String, Object> params, final StringBuilder builder) {
    boolean first = true;
    for (final ArraySelector item : items) {
      if (!first) {
        builder.append(",");
      }
      item.toString(params, builder);
      first = false;
    }
  }

  public Object execute(final Identifiable iCurrentRecord, final Object iResult, final CommandContext context) {
    final List<Object> result = new ArrayList<>();
    for (final ArraySelector item : items) {
      final Object index = item.getValue(iCurrentRecord, iResult, context);
      if (index == null) {
        return null;
      }

      if (index instanceof Integer) {
        result.add(MultiValue.getValue(iResult, ((Integer) index).intValue()));
      } else {
        if (iResult instanceof Map) {
          result.add(((Map) iResult).get(index));
        } else if (iResult instanceof Result && index instanceof String) {
          result.add(((Result) iResult).getProperty((String) index));
        } else if (MultiValue.isMultiValue(iResult)) {
          final Iterator<Object> iter = MultiValue.getMultiValueIterator(iResult);
          while (iter.hasNext()) {
            result.add(calculateValue(iter.next(), index));
          }
        } else {
          result.add(null);
        }
      }
      if (this.items.size() == 1 && result.size() == 1) {
        //      if (this.items.size() == 1) {
        return result.get(0);
      }
    }
    return result;
  }

  public Object execute(final Result iCurrentRecord, final Object iResult, final CommandContext context) {
    final List<Object> result = new ArrayList<>();
    for (final ArraySelector item : items) {
      final Object index = item.getValue(iCurrentRecord, iResult, context);
      if (index == null) {
        return null;
      }

      if (index instanceof Integer) {
        result.add(MultiValue.getValue(iResult, ((Integer) index).intValue()));
      } else {
        if (iResult instanceof Map) {
          result.add(((Map) iResult).get(index));
        } else if (iResult instanceof Result && index instanceof String) {
          result.add(((Result) iResult).getProperty((String) index));
        } else if (MultiValue.isMultiValue(iResult)) {
          final Iterator<Object> iter = MultiValue.getMultiValueIterator(iResult);
          while (iter.hasNext()) {
            result.add(calculateValue(iter.next(), index));
          }
        } else {
          result.add(null);
        }
      }
      if (this.items.size() == 1 && result.size() == 1) {
        //      if (this.items.size() == 1) {
        return result.get(0);
      }
    }
    return result;
  }

  private Object calculateValue(final Object item, final Object index) {
    if (index instanceof Integer) {
      return MultiValue.getValue(item, ((Integer) index).intValue());
    } else if (item instanceof Map) {
      return ((Map) item).get(index);
    } else if (item instanceof Result && index instanceof String) {
      return ((Result) item).getProperty((String) index);
    } else if (MultiValue.isMultiValue(item)) {
      final Iterator<Object> iter = MultiValue.getMultiValueIterator(item);
      final List<Object> result = new ArrayList<>();
      while (iter.hasNext()) {
        result.add(calculateValue(iter.next(), index));
      }
      return null;
    } else {
      return null;
    }
  }

  public ArraySingleValuesSelector copy() {
    final ArraySingleValuesSelector result = new ArraySingleValuesSelector(-1);
    result.items = items.stream().map(x -> x.copy()).collect(Collectors.toList());
    return result;
  }

  @Override
  protected Object[] getIdentityElements() {
    return new Object[] { items };
  }

  @Override
  protected SimpleNode[] getCacheableElements() {
    return items.toArray(new ArraySelector[items.size()]);
  }

  public void extractSubQueries(final SubQueryCollector collector) {
    if (items != null) {
      for (final ArraySelector item : items) {
        item.extractSubQueries(collector);
      }
    }
  }

  public void setValue(final Result currentRecord, final Object target, final Object value, final CommandContext context) {
    if (items != null) {
      for (final ArraySelector item : items) {
        item.setValue(currentRecord, target, value, context);
      }
    }
  }

  public void applyRemove(final Object currentValue, final ResultInternal originalRecord, final CommandContext context) {
    if (currentValue == null) {
      return;
    }
    final List values = this.items.stream().map(x -> x.getValue(originalRecord, null, context)).collect(Collectors.toList());
    if (currentValue instanceof List) {
      final List<Object> list = (List) currentValue;
      values.sort(this::compareKeysForRemoval);
      for (final Object val : values) {
        if (val instanceof Integer) {
          list.remove((int) (Integer) val);
        } else {
          list.remove(val);
        }
      }
    } else if (currentValue instanceof Set) {
      final Set set = (Set) currentValue;
      final Iterator iterator = set.iterator();
      final int count = 0;
      while (iterator.hasNext()) {
        final Object item = iterator.next();
        if (values.contains(count) || values.contains(item)) {
          iterator.remove();
        }
      }
    } else if (currentValue instanceof Map) {
      for (final Object val : values) {
        ((Map) currentValue).remove(val);
      }
    } else if (currentValue instanceof Result) {
      for (final Object val : values) {
        ((ResultInternal) currentValue).removeProperty("" + val);
      }
    } else {
      throw new CommandExecutionException("Trying to remove elements from " + currentValue + " (" + currentValue.getClass().getSimpleName() + ")");
    }
  }

  private int compareKeysForRemoval(final Object o1, final Object o2) {
    if (o1 instanceof Integer) {
      if (o2 instanceof Integer) {
        return (int) o2 - (int) o1;
      } else {
        return -1;
      }
    } else if (o2 instanceof Integer) {
      return 1;
    } else {
      return 0;
    }
  }
}
/* JavaCC - OriginalChecksum=991998c77a4831184b6dca572513fd8d (do not edit this line) */
