/*
  Copyright [2013-2014] eBay Software Foundation

   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 ru.yandex.webmaster3.core.xcelite.column;

import static org.reflections.ReflectionUtils.withAnnotation;

import java.lang.reflect.Field;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import org.reflections.ReflectionUtils;

import ru.yandex.webmaster3.core.xcelite.annotations.Column;
import ru.yandex.webmaster3.core.xcelite.annotations.Row;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;


public class ColumnsExtractor {

  private final Class<?> type;
  private Set<Col> columns;
  private Set<Col> colsOrdering;

  public ColumnsExtractor(Class<?> type) {
    this.type = type;
    columns = Sets.newLinkedHashSet();
    columnsOrdering();
  }

  private void columnsOrdering() {
    Row rowAnnotation = type.getAnnotation(Row.class);
    if (rowAnnotation == null || rowAnnotation.colsOrder() == null || rowAnnotation.colsOrder().length == 0) return;
    colsOrdering = Sets.newLinkedHashSet();
    for (String column : rowAnnotation.colsOrder()) {
      colsOrdering.add(new Col(column));
    }
  }

  @SuppressWarnings("unchecked")
  public void extract() {    
    Set<Field> columnFields = ReflectionUtils.getAllFields(type, withAnnotation(Column.class));
    for (Field columnField : columnFields) {
      Column annotation = columnField.getAnnotation(Column.class);
      Col col = null;
      if (annotation.name().isEmpty()) {
        col = new Col(columnField.getName(), columnField.getName());        
      } else {
        col = new Col(annotation.name(), columnField.getName());        
      }      
      
      if (annotation.ignoreType()) {
        col.setType(String.class);
      } else {
        col.setType(columnField.getType());
      }
      if (!annotation.dataFormat().isEmpty()) {
        col.setDataFormat(annotation.dataFormat());
      }
      columns.add(col);
    }   
    
    if (colsOrdering != null) {
      orderColumns();
    }
  }

  private void orderColumns() {
    // build temporary columns map and then use it to fill fieldName in colsOrdering set
    Map<String, Col> map = Maps.newHashMap();
    for (Col col : columns) {
      map.put(col.getName(), col);
    }
    
    for (Col col : colsOrdering) {
      if (columns.contains(col)) {
        Col column = map.get(col.getName());        
        column.copyTo(col);
      } else {
        throw new RuntimeException(String.format("Unrecognized column \"%s\" in Row columns ordering", col.getName()));
      }
    }
    
    if (colsOrdering.size() != columns.size()) {
      throw new RuntimeException(String.format("Not all columns are specified in Row columns ordering"));
    }
    columns = colsOrdering;
  }

  public LinkedHashSet<Col> getColumns() {
    return (LinkedHashSet<Col>) columns;
  }
}
