package com.inkasso.factoring.code.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.inkasso.factoring.code.dao.EntityGenerateDao;
import com.inkasso.factoring.code.domain.TableColumn;
import com.inkasso.factoring.code.model.DataSourceDTO;
import com.inkasso.factoring.code.model.PropertyDTO;
import com.inkasso.factoring.code.model.TableDTO;
import com.inkasso.factoring.code.service.EntityGenerateService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;



@Service
public class EntityGenerateServiceImpl implements EntityGenerateService {

	@Resource
	EntityGenerateDao entityGenerateDao;

	@Override
	public List<DataSourceDTO> getDataSources() {
		List<String> dataSourceList = entityGenerateDao.getDataSources();
		List<DataSourceDTO> resultList = new ArrayList<>();
		if (!CollectionUtils.isEmpty(dataSourceList)) {
			for (String source : dataSourceList) {
				if (!"information_schema".equalsIgnoreCase(source) && !"mysql".equalsIgnoreCase(source)
						&& !"performance_schema".equalsIgnoreCase(source)) {
					resultList.add(new DataSourceDTO(source));
				}
			}
		}
		return resultList;
	}
	
	@Override
	public List<TableDTO> getTablesByDataSource(String dataSource) {
		List<String> tablesList = entityGenerateDao.getTablesByDataSource(dataSource);
		List<TableDTO> resultList = new ArrayList<>();
		if (!CollectionUtils.isEmpty(tablesList)) {
			for (String table : tablesList) {
				resultList.add(new TableDTO(table));
			}
		}
		return resultList;
	}

	@Override
	public List<PropertyDTO> getColumnsByTableAndDataSource(String tableName, String dataSource) {
		List<TableColumn> tableColumns = entityGenerateDao.getColumnsByTableAndDataSource(tableName, dataSource);
		List<PropertyDTO> propertyDTOs = new ArrayList<>();
		if (!CollectionUtils.isEmpty(tableColumns)) {
			for (TableColumn tableColumn : tableColumns) {
				if (!"id".equalsIgnoreCase(tableColumn.getColumnName())
						&& !"optimisticLock".equalsIgnoreCase(tableColumn.getColumnName())) {
					PropertyDTO propertyDTO = new PropertyDTO();
					propertyDTO.setName(tableColumn.getColumnName());
					propertyDTO.setType(tableColumn.getDataType());
					propertyDTO.setLength(tableColumn.getLength());
					propertyDTO.setRequired(tableColumn.isRequired() ? "1" : "0");
					propertyDTO.setLabel(tableColumn.getLabel());
					propertyDTOs.add(propertyDTO);
				}
			}
		}
		return propertyDTOs;
	}
}
