package net.w_horse.excelpojo.excel.cellseeker;

import java.lang.annotation.Annotation;
import java.util.regex.Pattern;

import net.w_horse.excelpojo.ExcelPOJOException;
import net.w_horse.excelpojo.annotation.ExcelPOJOAnnotationParser;

import org.apache.poi.ss.usermodel.Sheet;

public class PointedCellSeeker extends AbstractCellSeeker {

	private String position;

	@Override
	public void set(Annotation annotation, ExcelPOJOAnnotationParser parser) {
		parser.setCellSeeker(annotation, this);
	}

	@Override
	public boolean verify() throws IllegalArgumentException, ExcelPOJOException {
		super.verify();
		if ((getPosition() == null) || getPosition().isEmpty()) {
			throw new IllegalArgumentException("The position is not specified.");
		}
		Pattern pattern = Pattern.compile("\\(\\s?[0-9]+\\s?,\\s?[0-9]+\\s?\\)");
		if (!pattern.matcher(getPosition()).matches()) {
			throw new IllegalArgumentException("There is a mistake in the format of the position specification. \n"
					+ "Format:(rowIndex, colIndex)  rowIndex={1,2,3,...}, colIndex={1,2,3,...}");
		}
		return true;
	}

	@Override
	public Object seekCellValue(Sheet sheet, Class<?> requiredType) throws ExcelPOJOException {
		return getCellValue(sheet, seekCellPosition(sheet), requiredType);
	}

	@Override
	protected Offset seekCellPosition(Sheet sheet) {
		return seekCellPosition(sheet, new Offset(), new Offset());
	}

	@Override
	protected Offset seekCellPosition(Sheet sheet, Offset basePosition, Offset offset) {
		return parsePosition(basePosition).add(offset);
	}


	@Override
	public void setValue(Sheet sheet, Object value) {
		setCellValue(getCell(sheet, seekCellPosition(sheet)), value, getConverter());
	}

	@Override
	public void setValue(Sheet sheet, Offset basePosition,
			Offset offset, Object value) {
		setCellValue(getCell(sheet, seekCellPosition(sheet, basePosition, offset)), value, getConverter());
	}

	private Offset parsePosition(Offset offset) {
		String positionStr = getPosition();
		String[] xy = positionStr.substring(1, positionStr.length() -1).split(",");
		int rowIndex = Integer.valueOf(xy[0].trim()) -1 + offset.rowIndex;
		int colIndex = Integer.valueOf(xy[1].trim()) -1 + offset.colIndex;
		return new Offset(rowIndex, colIndex);
	}

	public void setPosition(String position) {
		this.position = position;
	}

	public String getPosition() {
		return position;
	}

	public void setMargedRows(boolean connectedRows) {
	}

}
