var bricks = window.bricks || {};
bricks.Svg = class extends bricks.VBox {
	/*
	options:{
		rate:
		url:
		blink:false
		color:*
		blinkcolor:*
		blinktime:*
	}
	*/
	constructor(opts){
		opts.rate = opts.rate || 1;
		opts.cwidth = opts.rate;
		opts.cheight = opts.rate;
		opts.blinktime = opts.blinktime || 0.5;
		opts.dynsize = true;
		super(opts);
		if (! this.color) {
			this.color = bricks.app.get_color();
		}
		if (!this.blinkcolor){
			this.blinkcolor = bricks.app.get_bgcolor()
		}
		if (opts.url){
			this.set_url(opts.url);
		}
	}
	set_url(url){
		fetch(url)
			.then(response => response.text())
			.then(svgText => {
				if (svgText.startsWith("<svg ")){
					this.svgText = svgText;
					this.set_colored_svg(this.color);
					if (this.blink) this.start_blink();
				}
			});
	}
	set_ancent_color(e){
		var pstyle = getComputedStyle(this.parent);
		this.set_color(pstyle.color);
	}
	set_color(color){
		this.color = color;
		this.set_colored_svg(color);
	}
	set_blinkcolor(color){
		this.blinkcolor = color;
		this.blinktime = this.blinktime || 0.5;
	}
	set_colored_svg(color){
		this.cur_color = color;
		var svgText = bricks.obj_fmtstr({color: color}, this.svgText);
		this.dom_element.innerHTML = svgText;
	}
	_blink(){
		if (this.blinktime && this.blinkcolor) {
			if (this.cur_color == this.color){
				this.set_colored_svg(this.blinkcolor);
			} else {
				this.set_colored_svg(this.color);
			}
			this.blink_task = schedule_once(this._blink.bind(this), 
				this.blinktime);
		}
	}
	start_blink(){
		if (!this.blink_task){
			this._blink();
		}
	}
	end_blink(){
		this.blink_task = null;
	}
}

bricks.StatedSvg = class extends bricks.Svg {
	/* {
		states:[{state:aaa,url:} ,,],
		state:
	} */
	constructor(opts){
		super(opts);	
		if (this.states){
			if (! this.state){
				this.state = this.states[0].state;
			}
			var url = this.set_state(this.state);
			this.set_url(url);
		}
	}
	set_state(state){
		this.states.forEach(s => {
			if (s.state == state) this.set_url(s.url);
		});
	}
}
bricks.Factory.register('Svg', bricks.Svg);
bricks.Factory.register('StatedSvg', bricks.StatedSvg);

