class ServerComponent {
	constructor ()
	{
		this.fullUpdate = false;
	}	

	ajax(callback) {
		var self = this;
		this.url = Vvveb.Builder.iframe.contentWindow.location;
		//console.log(this.url);
		//console.log(this.content);
		self.element.animate({opacity: 0.85}, 50);

		$.ajax({
			url: this.url + '&_component_ajax=' + this.component + '&_component_id=' + this.index,
			type: 'post',
			data: {_component_content:this.content},
			//dataType: 'json',
			beforeSend: function() {
				$('.loading', element).removeClass('d-none');
				$('.button-text', element).addClass('d-none');
				if ($(element).is('button'))  {
					$(element).attr("disabled", "true");
				}
			},
			complete: function(data) {
				console.log(data);
				//$('#cart > button').button('reset');
			},
			success: function(data) {
				//$("header [data-v-component-cart]")[0].outerHTML = data;
				if (callback) callback(data);
			},
			error: function(xhr, ajaxOptions, thrownError) {
				alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
			}
		})
		.always(function(data) {
				//$('#cart > button').button('reset');
		})
		.done(function(data) {
//				self.element[0].outerHTML = data;
//				self.element[0].click();

				//var newElement = self.element.before(data);
				var newElement = $(data);
				//set fixed height for parent to avoid page flicker
				var parent = self.element.parent();
				//
				
				parent.height(parent.height());
				//full update
				if (this.fullUpdate)  {
					self.element.replaceWith(newElement);
				} else {
					self.element.html(newElement.html());
					self.element.height(self.element.height());
				}
				
				setTimeout(function () {
					//if (this.fullUpdate) 
					parent.height("");
					self.element.height("");
					self.element.animate({opacity: 1}, 50);
					self.element.click();
				}, 250);
				

				if (callback) callback(data);
		})
		.fail(function(xhr, ajaxOptions, thrownError) {
				alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
		});
	}		
	
	onChange(element, property, value, input)  {

				//search through all components of the same type on page and get index
				var selector = this.attributes
								.map(el => {return "[" + el + "]";})
								.join(",");
				
				
				this.component = this.attributes[0].replace("data-v-component-", "");
				this.index = $(selector,Vvveb.Builder.frameBody).index(element);
				this.content = element[0].outerHTML;
				this.element = element;
				
				this.ajax();
				return element;
	}
};

export {
  ServerComponent
};
