package com.apobates.forum.utils.selenium;

import java.math.BigDecimal;
import java.math.RoundingMode;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 此类的计算只适用于元素位于屏幕的中心
 * 
 * @author xiaofanku
 * @since 20191222
 */
public class SeleniumCoordinate {
	//左上角的X坐标值
	private final int leftTopX;
	//截取元素的宽度
	private final int width; 
	//缩放比
	private final BigDecimal resizeScale;
	//原来的宽度/浏览器中元素的宽度
	private final int elementWidth;
	private final static Logger logger = LoggerFactory.getLogger(SeleniumCoordinate.class);
	
	/**
	 * 
	 * @param dimensionWidth  selenium中设置的窗口宽度
	 * @param fullScreenWidth 截取整屏时图的宽度
	 * @param elementWidth    浏览器中元素的宽度
	 */
	public SeleniumCoordinate(int dimensionWidth, int fullScreenWidth, int elementWidth){
		this.elementWidth = elementWidth;
		//缩放比new BigDecimal("1.17");
		BigDecimal rs = new BigDecimal(fullScreenWidth).divide(new BigDecimal(dimensionWidth), 2, BigDecimal.ROUND_FLOOR);
		this.width = rs.multiply(new BigDecimal(elementWidth)).intValue();//(int)(elementWidth * resizeScale);
		this.leftTopX = (fullScreenWidth / 2) - (this.width / 2);
		this.resizeScale = rs;
	}
	
	/**
	 * 左上角的X坐标值
	 * @return
	 */
	public int getLeftTopX() {
		return leftTopX;
	}
	
	/**
	 * 截取元素的宽度
	 * @return
	 */
	public int getWidth() {
		return width;
	}
	
	/**
	 * 计算的缩放比
	 * @return
	 */
	public BigDecimal getResizeScale() {
		return resizeScale;
	}
	
	@Override
	public String toString() {
		return "SeleniumCoordinate [leftTopX=" + leftTopX + ", width=" + width + "]";
	}
	
	/**
	 * 浏览器中元素的宽度
	 * @return
	 */
	public int getElementWidth() {
		return elementWidth;
	}
	
	/**
	 * 计算缩放后,要截取的元素高度
	 * @param elementHeight 浏览器中元素的高度
	 * @return
	 */
	public int getResizeHeightValue(int elementHeight){
		logger.info("---------------------calc resize height start");
		logger.info("element height: "+elementHeight+", width: "+elementWidth);
		//V2: 图片的宽和高比
		BigDecimal rs = new BigDecimal(elementHeight).divide(new BigDecimal(elementWidth), 2, BigDecimal.ROUND_FLOOR);
		logger.info("height/width: "+rs);
		BigDecimal data = rs.multiply(new BigDecimal(width));
		data = data.setScale(0, RoundingMode.UP);
		logger.info("---------------------calc resize height end");
		return data.intValue();
	}
	
	/**
	 * 计算缩放后,要截取起始Y坐标, 左上角Y坐标
	 * @param originalY
	 * @return
	 */
	public int getLeftTopY(int originalY){
		logger.info("---------------------calc resize left top Y start");
		logger.info("top height: "+originalY+", width: "+elementWidth);
		BigDecimal rs = new BigDecimal(originalY).divide(new BigDecimal(elementWidth), 3, BigDecimal.ROUND_FLOOR);
		logger.info("height/width: "+rs);
		BigDecimal data = rs.multiply(new BigDecimal(width));
		data = data.setScale(0, RoundingMode.UP);
		logger.info("---------------------calc resize left top Y end");
		return data.intValue();
	}
}
