<?php
//
// synchronizacja do serwera postgres GIS
//

include_once('se-lib/DB_Dump.php');
include_once('se-lib/UsersHelper.php');




class GIS_OPT_STRUCTURES {



		function init() {
			
				$this->graph = new stdClass();
				$this->graph->htmlID = 'graph_proces_id_' . $id_proces;
				$this->graph->procesTreeFlat = array();
				$this->graph->procesTreeGoto = array();
				$this->graph->treeItems = array();

				$this->graph->elements = new stdClass();
				$this->graph->elements->nodes = array();
				$this->graph->elements->edges = array();
			
		}


		function set_mysql_zas_id($mysql_zas_id) {
			$this->mysql_zas_id=$mysql_zas_id;
		}


		function set_gis_zas_id($gis_zas_id) {
			$this->gis_zas_id=$gis_zas_id;
			$this->gdb=DB::getDB($this->gis_zas_id);

		}
		
		
		function get_opt_objects($src_table,$src_index,$src_name,$map_table_id,$map_table_name,$parent_table_id,$parent_table,$limit=null,$ids_ok) {
			
			
			$sql='select \''.$src_table.'\' as src_table , "'.$src_index.'" as src_index ';
			if(!empty($src_name)) $sql.=', "'.$src_name.'" as src_name ';
			$sql.=', "'.$parent_table_id.'"  as parent_table_id ,  \''.$parent_table.'\' as parent_table  from "'.$src_table.'" '.$limit.' ;';
			$res=$this->gdb->query($sql);
			while($h=$this->gdb->fetch($res)) {
				if(!empty($limit)) {
					//bierzemy wszystkie rekordy bo byl limit
					$arr[]=$h;
					$this->tables->$src_table->src_index[]=$h->src_index;

				} else {
					//tylko te rekordy dla ktorych byly powiazania
					if(in_array($h->parent_table_id, $this->tables->$parent_table->src_index)) {
						$this->tables->$src_table->src_index[]=$h->src_index;
			//			echo "<br> <font color=green>id ".$h->parent_table_id." IS found in ".$parent_table." parent table</font>";
						$arr[]=$h;
					} //else echo "<br> id ".$h->parent_table_id." not found in ".$parent_table." parent table";
				}
				
			}
			return $arr;
			
		}
		
		
		function get_opt_objects_parent($src_table,$src_index,$src_name,$map_table_id,$map_table_name,$parent_table_id,$parent_table,$limit=null,$child_table,$child_joinfield,$child_index){
			$i=0;
			$where_in=implode(",", $this->tables->$child_table->src_index);
			
			$sql='select \''.$src_table.'\' as src_table , t1."'.$src_index.'" as src_index ';
			if(!empty($src_name)) $sql.=', t1."'.$src_name.'" as src_name ';
			$sql.=', t1."'.$parent_table_id.'"  as parent_table_id ,  \''.$parent_table.'\' as parent_table  from "'.$src_table.'"  as t1
			  inner join "'.$child_table.'" as t2 on t1."'.$src_index.'"=t2."'.$child_joinfield.'" 
			 where  t2."'.$child_index.'" in ('.$where_in.') ;';
			
			echo "<br> sql: ".$sql;
			$res=$this->gdb->query($sql);
			while($h=$this->gdb->fetch($res)) {
					$i++;
//				if($i>5) continue;
					if(!in_array($h->src_index, $this->tables->$src_table->src_index)) {
					$this->tables->$src_table->src_index[]=$h->src_index;
					
						$arr[]=$h;
					}

			}
			return $arr;
			
		}
		
		
		function add_array_to_graph($array,$PROCES_INIT) {
			
			foreach($array as $link) { 
				if(!empty($link->parent_table_id)) $parent=$link->parent_table.$link->parent_table_id; else $parent=null;
				self::graph__addNodeID($link->src_table.$link->src_index, $this->graph,$link->src_name,null,$parent,$PROCES_INIT);
			}
 
			
		}
		
		
			function graph__addNodeID($id, $graph,$name=null,$path,$parent=null,$type) {
		//if (!array_key_exists($id, $this->graph->treeItems)) {
			$this->graph->treeItems[$id]= true;
			if(empty($name)) $name=$id; //else $name.="".$id;
			if(!empty($path))  { $name=$name." ".implode(',', $path);// $path=array(); 
			}
			//DEBUG_S(-3,'added id,name,path,parent',array($id,$name,$path,$parent),__FILE__,__FUNCTION__,__LINE__);

			if($type=='PROCES_INIT') $type_init='procesInit'; else $type_init=null;
			//echo $type_init.$id;
			$this->graph->elements->nodes[] = array('data'=>array('id'=>"".$id."", 'name'=>$name , 'type'=>$type_init));
			

			//echo "<br> w AddNode:ID".$id." parent".$parent;
		//}
		   if(!empty($parent)) {
		   	
		   	$this->graph->elements->edges[] = array('data'=>array('source'=>$parent, 'target'=>$id  ));
		   }
		   
		 

	}


	function to_html() {
	
	foreach($this->graph->elements->edges as $data) {
	 //  DEBUG_S(-3,'data',$data,__FILE__,__FUNCTION__,__LINE__);
		if(empty($this->graph->treeItems[$data['data']['source']])) {
			self::graph__addNodeID($data['data']['source'], $this->graph,$data['data']['source'],null,null,null);
			echo "<br> Empty ".$data['data']['source'];
		}

		
	}
	
	DEBUG_S(-3,'Graph obj',$this->graph,__FILE__,__FUNCTION__,__LINE__);
	DEBUG_S(-3,'tables',$this->tables,__FILE__,__FUNCTION__,__LINE__);

	?>	
		<style type="text/css">
	#<?php echo $this->graph->htmlID; ?>_wrap {
	position:relative;
	width:1100px;
	margin:0 auto;
	border:1px solid #ccc;
}
#<?php echo $this->graph->htmlID; ?> {
	height:560px;
	border-bottom:1px solid #ccc;
}
#<?php echo $this->graph->htmlID; ?>_info {
	padding:3px;
}
#<?php echo $this->graph->htmlID; ?>_wrap .actions { position:absolute; top:20px; left:-40px; margin:0; padding:0; list-style:none; }
#<?php echo $this->graph->htmlID; ?>_wrap .actions button { border-radius:0; background:#fff; border:1px solid #ccc; }
</style>

<script src="./stuff/cytoscape.js/arbor.js"></script>
<script src="./stuff/cytoscape.js/cytoscape.js"></script>
<script>
jQuery(loadInfo = function(nodeID){
	$.ajax({
		url: 'index.php?MENU_INIT=GRAPH_VIEW_PROCES&id_proces=<?php echo $id_proces; ?>&ajaxTask=getInfo&id=' + nodeID + '&HEADER_NOT_INIT=YES',
		type: 'GET',
		dataType: 'text',
		data: '',
		async: true,
		success: function (data) {
			jQuery('#<?php echo $this->graph->htmlID; ?>_info').html(data);
		},
		error: function (err) {
			console.log('err');
		}
	});
});
jQuery(loadCy = function(){
	jQuery('#<?php echo $this->graph->htmlID; ?>').cytoscape({
		layout: {
			name: 'arbor'
		},
		style: cytoscape.stylesheet()
			.selector('node')
				.css({
					'shape': 'rectangle',
					'width': '10px', 'height': '8px',
					'font-size': '10px',
					'content': 'data(name)',
					'text-valign': 'center',
					'color': 'white',
					'text-outline-width': 2,
					'text-outline-color': '#888'
				})
			.selector('edge')
				.css({
					'target-arrow-shape': 'triangle'
				})
			.selector(':selected')
				.css({
					'background-color': 'black',
					'line-color': 'black',
					'target-arrow-color': 'black',
					'source-arrow-color': 'black'
				})
			.selector('.faded')
				.css({
					'opacity': 0.25,
					'text-opacity': 0
				})
			.selector('edge.neighborhood')
				.css({
					'background-color': 'blue',
					'color': 'orange'
				})
			.selector('node.procesInit')
				.css({
					'background-color': 'red',
					'text-outline-color': 'red',
					'font-weight': 'bold'
				}),

		elements: <?php echo json_encode($this->graph->elements); ?>,

		ready: function(){
			var cy = this;
			window.cy_<?php echo $this->graph->htmlID; ?> = this;

			cy.elements("node[type = 'procesInit']").addClass('procesInit');
			cy.elements("node[lvl > 1]").hide();

			cy.elements().unselectify();

			cy.on('tap', 'node', function(e){
				//console.log('on tap node', e)
				var node = e.cyTarget;
				var neighborhood = node.neighborhood().add(node);

				var nodeID = node.id();
				loadInfo(nodeID);

				cy.elements().addClass('faded').unselect();
				neighborhood.removeClass('faded');
				node.select();

				cy.edges().removeClass('neighborhood');
				node.connectedEdges().addClass('neighborhood');

				neighborhood.show();

				cy.center(neighborhood);
			});

			cy.on('tap', function(e){
				if (e.cyTarget === cy){
					cy.elements().removeClass('faded');
				}
			});
		},
		showOverlay: false
	});
});

jQuery(document).ready(function(){
	loadCy();

	var parent = $('#<?php echo $this->graph->htmlID; ?>')
		.parent()
	parent.find('.actions .cy-refresh')
		.on('mousedown touchstart', function(){
			loadCy();

			cy.attr('style', '');
		});
	parent.find('.actions .cy-zoom-plus')
		.on('mousedown touchstart', function(){
			window.cy_<?php echo $this->graph->htmlID; ?>.zoom(window.cy_<?php echo $this->graph->htmlID; ?>.zoom() + 0.1);
		});
  parent.find('.actions .cy-zoom-minus')
		.on('mousedown touchstart', function(){
			window.cy_<?php echo $this->graph->htmlID; ?>.zoom(window.cy_<?php echo $this->graph->htmlID; ?>.zoom() - 0.1);
		});
});
</script>

<div id="<?php echo $this->graph->htmlID; ?>_wrap">
	<div id="<?php echo $this->graph->htmlID; ?>"></div>
	<div id="<?php echo $this->graph->htmlID; ?>_info"></div>
	<ul class="actions">
		<li><button class="btn cy-refresh"><i title="Refresh" class="ico-refresh"></i></button></li>
		<li><button class="btn cy-zoom-plus"><i title="Zoom +" class="ico-plus"></i></button></li>
		<li><button class="btn cy-zoom-minus"><i title="Zoom -" class="ico-minus"></i></button></li>
	</ul>
</div>
<?
		
	}
	
	
	
 
	
}


function GIS_OPT_STRUCTURES() {
	global $db,$gdb;

	$mysql_zas_id=36;
	$gis_zas_id=13102;
	
	
	
	$db = DB::getDB();
	$gdb= DB::getDB($gis_zas_id);
	
	
	DEBUG_S(-3,'db',$db);
	DEBUG_S(-3,'gis',$gdb);
		
	 $cp=new GIS_OPT_STRUCTURES;
	 $cp->init();
	 $cp->set_gis_zas_id($gis_zas_id);
	 
	 
	 
	 $wezly=$cp->get_opt_objects('opt_przelacznice_mufy','id_0','Nazwa','id_wezel','Rozdzielcza_wezly','id_opt_lokalizacja','opt_lokalizacje',"where \"Nazwa\" like '%test%'");




	 $tacki=$cp->get_opt_objects('opt_tacki','id_0',null,null,null,'id_przelac','opt_przelacznice_mufy');
	 $spawy=$cp->get_opt_objects('opt_spawy','id_0',null,null,null,'id_tacka','opt_tacki');
	 $wlokna=$cp->get_opt_objects('opt_wlokna','id',null,null,null,'id_spaw_a','opt_spawy');
	 $wlokna2=$cp->get_opt_objects('opt_wlokna','id',null,null,null,'id_spaw_b','opt_spawy');

	
	 $spawy_b=$cp->get_opt_objects_parent('opt_spawy','id_0',null,null,null,'id_tacka','opt_tacki','1=1','opt_wlokna','id_spaw_b','id'); //chce znalezc te sprawy ktore sa w wloknach jako B
	 $spawy_b2=$cp->get_opt_objects_parent('opt_spawy','id_0',null,null,null,'id_tacka','opt_tacki','1=1','opt_wlokna','id_spaw_a','id'); //chce znalezc te sprawy ktore sa w wloknach jako B

	 $tacki_b=$cp->get_opt_objects_parent('opt_tacki','id_0',null,null,null,'id_przelac','opt_przelacznice_mufy','1=1','opt_spawy','id_tacka','id_0'); //chce znalezc te sprawy ktore sa w wloknach jako B	
	
	 $wezly_b=$cp->get_opt_objects_parent('opt_przelacznice_mufy','id_0','Nazwa','id_wezel','Rozdzielcza_wezly','id_opt_lokalizacja','opt_lokalizacje','1=1','opt_tacki','id_przelac','id_0');	 

	 
	 $cp->add_array_to_graph($wezly,'PROCES_INIT');
	 $cp->add_array_to_graph($tacki,null);
	 $cp->add_array_to_graph($spawy,null);
	 $cp->add_array_to_graph($wlokna,null);
	 $cp->add_array_to_graph($wlokna2,null);

	 $cp->add_array_to_graph($spawy_b,null);
	 $cp->add_array_to_graph($spawy_b2,null);

	 $cp->add_array_to_graph($tacki_b,null);
	 $cp->add_array_to_graph($wezly_b,'PROCES_INIT');
	 
	 
	 DEBUG_S(-3,'Wezly do dodania',$wezly,__FILE__,__FUNCTION__,__LINE__);
	 
	 $cp->to_html();
	 
	 die();
	 
	 	//	  foreach($obj->INTERNAL_LINK as $link) graph__addNodeID($id, $graph,$tree->Viev_Zpc[$link]->DESC,null,$link,null);
		//	  foreach($obj->EXTERNAL_LINK as $link) graph__addNodeID($link, $graph,$tree->Viev_Zpc[$link]->DESC,null,$id,'PROCES_INIT');

	 
	 
	 
	}
	
	
	

	
	
	
	
	
	


?>

