/**
 * Created by rockyl on 2018/11/6.
 *
 * todo 如果isUsedToMask，就禁用缓存
 */

import Renderer from "./Renderer";
import {color} from "scilla";

/**
 * 图形渲染组件
 */
export default class GraphicRenderer extends Renderer {
	fillColor: color = '#42bce4';
	borderColor: color = '#0899d0';
	borderWidth = 0;

	//是否为mask
	isUsedToMask = false;
	//是否显示mask
	maskVisible = false;

	protected getUseCacheMode(){
		return this._useCacheMode && !this.isUsedToMask;
	}

	/**
	 * 获取图形尺寸
	 */
	protected getRenderSize(): any {
		return {width: 0, height: 0};
	}

	/**
	 * @inheritDoc
	 */
	protected beforeDraw() {
		super.beforeDraw();
		this.applyStyle();
		this.context.beginPath();
	}

	/**
	 * @inheritDoc
	 */
	protected draw() {
		super.draw();

		if (this.isUsedToMask) {
			this._context.clip();
			this.maskVisible && this.fillAndStoke()
		} else {
			this.fillAndStoke()
		}
	}

	/**
	 * 应用渲染样式
	 */
	protected applyStyle() {
		const {context, fillColor, borderColor, borderWidth} = this;

		context.fillStyle = fillColor;
		if (borderWidth > 0) {
			context.strokeStyle = borderColor;
			context.lineWidth = borderWidth;
		}
	}

	/**
	 * 绘制
	 */
	protected fillAndStoke() {
		const {context, borderWidth} = this;

		context.fill();
		if (borderWidth > 0) {
			context.stroke();
		}
	}

	/**
	 * @inheritDoc
	 */
	protected drawClip() {
		this.isUsedToMask && this.context.save();
	}

	/**
	 * @inheritDoc
	 */
	afterUpdate() {
		this.isUsedToMask && this.context.restore();
	}

	measureBounds() {
		if(this.entity.name == 'content'){
			console.log();
		}

		if (!this.dirty) {
			return;
		}

		this._margin = this.borderWidth;

		const {bounds, transform: {explicitWidth: tWidth, explicitHeight: tHeight}} = this;
		const {width: sWidth, height: sHeight} = this.getRenderSize();

		bounds.width = isNaN(tWidth) ? sWidth : tWidth;
		bounds.height = isNaN(tHeight) ? sHeight : tHeight;

		super.measureBounds();
	}
}
