Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJkNjcyOWZhYi0xZmQ0LTQyYmMtYjQ0MS1hY2YxYzcxYWFmMWEiLCJpZCI6MTEwNzEsImlhdCI6MTYzMDk5MzEyNX0.fcsH4S5hE0ye9s-2cOFMyObiHlhu9vqjWdlYfGkv5gU';
    //////////////////////////////////////////////////////////////////////////
    // Creating the Viewer
    //////////////////////////////////////////////////////////////////////////

     var viewer = new Cesium.Viewer('cesiumContainer', {
         scene3DOnly: true,
         selectionIndicator: false,
		 timeline: false,
		 animation: false,
		 shadow: false,
		 // // Set default basemap
		 imageryProvider : Cesium.ArcGisMapServerImageryProvider({
    url : 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',
	enablePickFeatures: false
}),        
		 baseLayerPicker: true
		 
     });
     viewer.clock.shouldAnimate = false;
	 viewer.scene.globe.enableLighting = false;
     viewer.clock.startTime = Cesium.JulianDate.fromIso8601("2019-09-20T13:00:00Z");
     viewer.clock.stopTime = Cesium.JulianDate.fromIso8601("2019-09-20T13:20:00Z");
     viewer.clock.currentTime = Cesium.JulianDate.fromIso8601("2019-09-20T13:00:00Z");
	 document.getElementById("legend").style.display = "none"; //defining legends hidden by default
	 
    //////////////////////////////////////////////////////////////////////////
    // Configuring the camera
    //////////////////////////////////////////////////////////////////////////
var initialPosition = Cesium.Cartesian3.fromDegrees(16.368084, 48.183257, 360);
     var initialOrientation = new Cesium.HeadingPitchRoll.fromDegrees(249, -17, 0);
     var homeCameraView = {
         destination : initialPosition,
         orientation : {
            heading : initialOrientation.heading,
            pitch : initialOrientation.pitch,
            roll : initialOrientation.roll
         }
      };
    // // Set the initial view
     viewer.scene.camera.setView(homeCameraView);
	// set home button to initial view 
	 
	 viewer.homeButton.viewModel.command.beforeExecute.addEventListener(function (e) {
        e.cancel = true;
         viewer.scene.camera.flyTo(homeCameraView);
     });
	viewer.camera.changed.addEventListener(function() {

  var deg = Math.round( Cesium.Math.toDegrees(viewer.camera.heading))
  console.log('Heading:', deg)

  var deg = Math.round( Cesium.Math.toDegrees(viewer.camera.pitch))
  console.log('Pitch:', deg)
  
  var deg = Math.round( Cesium.Math.toDegrees(viewer.camera.roll))
  console.log('Roll:', deg)
  
});
    //////////////////////////////////////////////////////////////////////////
    // Load 3D Tileset
    //////////////////////////////////////////////////////////////////////////

    var building = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({url: 'https://w2.iaf-ex.hft-stuttgart.de/CesiumData/3DTiles/Buildings/BuildingSolid/Meidling_Vienna/tileset.json'}));
	var outdoorbuildinginstallation = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({url: 'https://w2.iaf-ex.hft-stuttgart.de/CesiumData/3DTiles/Buildings/BuildingInstallation/Meidling_Vienna/tileset.json'}));
	var roofsurface = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({url: 'https://w2.iaf-ex.hft-stuttgart.de/CesiumData/3DTiles/Buildings/RoofSurface/Meidling_Vienna/tileset.json'}));
	var roofdefaultstyle = new Cesium.Cesium3DTileStyle({color : "color('#990000')"});
		roofsurface.style = roofdefaultstyle;
      // set roof height and load roof tile 
				roofsurface.readyPromise.then(function(tileset) {
                 height = 0.02;
                 viewer.scene.primitives.add(tileset);
                 var cartographic = Cesium.Cartographic.fromCartesian(tileset.boundingSphere.center);
                 var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
                 var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, height);
                 var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
                 tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
					console.log(error);
             });
			roofsurface.show =true;
	var landuse = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({url: 'https://w2.iaf-ex.hft-stuttgart.de/CesiumData/3DTiles/LandUse/Meidling_Vienna/tileset.json'}));
	
	 

	landuse.show = false;
		
	
	function showbuildings() {
	 	 if (document.getElementById('buildings').checked) {building.show = true; outdoorbuildinginstallation.show = true;
	roofsurface.show = true; 
	} 
	 else {building.show = false; outdoorbuildinginstallation.show = false;
	roofsurface.show = false;}
	 }
	 
	       // Style landuse Tileset
 	 
	 var landusestyle = new Cesium.Cesium3DTileStyle({
         color : {
            conditions : [
					["${NUTZUNG_L0} === 'Agriculture'", "color('#785027')"],
                    ["${NUTZUNG_L0} === 'Commercial (Mixed Use)'", "color('#B7950B')"],
                    ["${NUTZUNG_L0} === 'Industrial and Commercial'", "color('#F4D03F')"],
                    ["${NUTZUNG_L0} === 'Natural Space'", "color('#DAF7A6')"],
                    ["${NUTZUNG_L0} === 'Other Traffic Use'", "color('#868683')"],
                    ["${NUTZUNG_L0} === 'Recreational Facility'", "color('#1E8449')"],
                    ["${NUTZUNG_L0} === 'Residential (Mixed Use)'", "color('#E74C3C')"],
                    ["${NUTZUNG_L0} === 'Social Infrastructure'", "color('#6C3483')"],
                    ["${NUTZUNG_L0} === 'Street Space'", "color('#D2D1CD')"],
                    ["${NUTZUNG_L0} === 'Technical (Engineering) Infrastructure'", "color('#D4E6F1')"],
                    ["${NUTZUNG_L0} === 'Water Body'", "color('#5DADE2')"],
                    ]
         },
		 show: true
     });

     function showlanduse() {
        if (document.getElementById('landuse').checked) {
             landuse.show = true;
			 landuse.style = landusestyle;
			 document.getElementById("legend").style.display = "block";
			 } 
		else {
              landuse.show = false;
			  document.getElementById("legend").style.display = "none";
			 }
        }
	 
    //////////////////////////////////////////////////////////////////////////
    // Style 3D Tileset
    //////////////////////////////////////////////////////////////////////////
	
	  var buildingdefaultstyle = new Cesium.Cesium3DTileStyle({
         color : "color('WHITE')",
		  show: true
     });

	 var heatenergydemandstyle = new Cesium.Cesium3DTileStyle({
         color : {
            conditions : [
                        [' Number(${nrg_epc_primaryEnergyDemandValue_s1}) >= 225', "color('red')"],
                        [' Number(${nrg_epc_primaryEnergyDemandValue_s1}) >= 125', "mix(color('yellow'), color('red'), (Number(${nrg_epc_primaryEnergyDemandValue_s1}) -125) / 125)"],
                        [' Number(${nrg_epc_primaryEnergyDemandValue_s1}) >= 1', "mix(color('green'), color('yellow'), (Number(${nrg_epc_primaryEnergyDemandValue_s1}) ) / 125)"],
                        [' Number(${nrg_epc_primaryEnergyDemandValue_s1}) < 1', "color('#ffffff1A')"],
                        ['true', "color('#ffffff1A')"]
                        ]			
	
         },
		 show: true
     });
	 	
	 var heatdemandstyle = document.getElementById('heatdemand');
     function showheatdemand() {
	 if (document.getElementById('pvpotential').checked) {
		 alert("At a time only one analysis selection is possible. Please uncheck the current analysis selection first and then re-select this option.");
  return false;
}
else

		 {
	 if (document.getElementById('buildings').checked) {
        if (heatdemandstyle.checked) {
			outdoorbuildinginstallation.show = false;
			 roofsurface.show = false;
             building.style = heatenergydemandstyle;
			 document.getElementById("heat-demand-legend").style.display = "block";
			 		      } 
		else {
			  outdoorbuildinginstallation.show = true;
			  roofsurface.show = true;
              building.style = buildingdefaultstyle;
			  roofsurface.style = roofdefaultstyle;
			  document.getElementById("heat-demand-legend").style.display = "none";
			 		      }
        }
	 else {
  alert("Please select the buildings layer under 3D city model first, and then re-select this option.");
  return false;
}
	 }
	 }
	 
	  var roofPVstyle = new Cesium.Cesium3DTileStyle({
         color : {
            conditions : [
                        [' Number(${PV_yield}) >= 10', "color('green')"],
                          [' Number(${PV_yield}) >= 5', "mix(color('yellow'), color('green'), (Number(${PV_yield}) -5) /5)"],
                          [' Number(${PV_yield}) >= 1', "mix(color('red'), color('yellow'), (Number(${PV_yield}) ) /5)"],
                          [' Number(${PV_yield}) < 1', "color('red')"],
                          ['true', 'rgb(0, 0, 0)']
                      ] 			
	
         },
		 show: true
     });
		
	var pvpotentialstyle = document.getElementById('pvpotential');
     function showpvpotential(){
	 if (document.getElementById('heatdemand').checked) {
		 alert("At a time only one analysis selection is possible. Please uncheck the current analysis selection first and then re-select this option.");
  return false;
}
else {
		 if (document.getElementById('buildings').checked) {
        if (pvpotentialstyle.checked) {
			outdoorbuildinginstallation.show = false;
			roofsurface.show = true;
			 roofsurface.style = roofPVstyle;
             document.getElementById("pv-potential-legend").style.display = "block";
			 		      } 
		else {
			outdoorbuildinginstallation.show = true;
			roofsurface.show = true;
			roofsurface.style = roofdefaultstyle;
              document.getElementById("pv-potential-legend").style.display = "none";
			 		      }
        }
			 else {
  alert("Please select the buildings layer under 3D city model first, and then re-select this option.");
  return false;
}
	 }
	 }
	 

    //////////////////////////////////////////////////////////////////////////
    // Custom mouse interaction for highlighting and selecting
    //////////////////////////////////////////////////////////////////////////


//Selecting a Building
var Pickers_3DTile_Activated = true;
// Information about the currently highlighted feature
function active3DTilePicker() {
    var highlighted = {
        feature: undefined,
        originalColor: new Cesium.Color()
    };
    // Information about the currently selected feature
    var selected = {
        feature: undefined,
        originalColor: new Cesium.Color()
    };

    // An entity object which will hold info about the currently selected feature for infobox display
    var selectedEntity = new Cesium.Entity();

    // Get default left click handler for when a feature is not picked on left click
    var clickHandler = viewer.screenSpaceEventHandler.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    // Color a feature yellow on hover.
    viewer.screenSpaceEventHandler.setInputAction(function onMouseMove(movement) {
        if (Pickers_3DTile_Activated) {
            // If a feature was previously highlighted, undo the highlight
            if (Cesium.defined(highlighted.feature)) {
                highlighted.feature.color = highlighted.originalColor;
                highlighted.feature = undefined;
            }
            // Pick a new feature
            var picked3DtileFeature = viewer.scene.pick(movement.endPosition);
            if (!Cesium.defined(picked3DtileFeature)) {
                               return;
            }
  
            // Highlight the feature if it's not already selected.
            if (picked3DtileFeature !== selected.feature) {
                highlighted.feature = picked3DtileFeature;
                Cesium.Color.clone(picked3DtileFeature.color, highlighted.originalColor);
                picked3DtileFeature.color = Cesium.Color.BLANCHEDALMOND;
            }
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    // Color a feature on selection and show metadata in the InfoBox.
    viewer.screenSpaceEventHandler.setInputAction(function onLeftClick(movement) {

        if (Pickers_3DTile_Activated) {
            // If a feature was previously selected, undo the highlight
            if (Cesium.defined(selected.feature)) {
                selected.feature.color = selected.originalColor;
                selected.feature = undefined;
                var options = null;
            }
            // Pick a new feature
            var picked3DtileFeature = viewer.scene.pick(movement.position);
            if (!Cesium.defined(picked3DtileFeature)) {
                clickHandler(movement);
                return;
            }
            // Select the feature if it's not already selected
            if (selected.feature === picked3DtileFeature) {
                return;
            }
            selected.feature = picked3DtileFeature;
            // Save the selected feature's original color
            if (picked3DtileFeature === highlighted.feature) {
                Cesium.Color.clone(highlighted.originalColor, selected.originalColor);
                highlighted.feature = undefined;
            } else {
                Cesium.Color.clone(picked3DtileFeature.color, selected.originalColor);
            }
            // Highlight newly selected feature
            picked3DtileFeature.color = Cesium.Color.BLANCHEDALMOND;
            // Set feature infobox description - if condition is for different info box for different entities such as building solids, roofs, landuse etc
			
			if (picked3DtileFeature.getProperty('SemanticType') === "Building") {
                
			
            var featureName = "Meidling 3D Viewer - Building";
            selectedEntity.name = featureName;
            selectedEntity.description = 'Loading <div class="cesium-infoBox-loading"></div>';

            viewer.selectedEntity = selectedEntity;
            selectedEntity.description =
                '<table class="cesium-infoBox-defaultTable"><tbody>' +
                '<tr><th>Building ID</th><td>' + picked3DtileFeature.getProperty('gml_id') + '</td></tr>' +
                '<tr><th>Building Class Code</th><td>' + picked3DtileFeature.getProperty('citygml_class') + '</td></tr>' +
                '<tr><th>Building Type</th><td>' + picked3DtileFeature.getProperty('buildingType') + '</td></tr>' +
                '<tr><th>Year of Construction</th><td>' + picked3DtileFeature.getProperty('citygml_year_of_construction') + '</td></tr>' +
				'<tr><th>Roof Type</th><td>' + picked3DtileFeature.getProperty('citygml_roof_type') + '</td></tr>' +
				'<tr><th>Building Storeys Above Ground</th><td>' + picked3DtileFeature.getProperty('citygml_storeys_above_ground') + '</td></tr>' +
				'<tr><th>Building Storeys Below Ground</th><td>' + picked3DtileFeature.getProperty('citygml_storeys_below_ground') + '</td></tr>' +
				'<tr><th>Estimated Total Residents</th><td>' + picked3DtileFeature.getProperty('num_residents') + '</td></tr>' +
				'<tr><th>Building Height</th><td>' + picked3DtileFeature.getProperty('citygml_measured_height') + ' ' + 'm' + '</td></tr>' +
				'<tr><th>Footprint Area </th><td>' + picked3DtileFeature.getProperty('footprintArea') + ' ' + 'm²' + '</td></tr>' +
                '<tr><th>Building Volume</th><td>' + picked3DtileFeature.getProperty('lod2Volume') + ' ' + 'm³' + '</td></tr>' +
				'<tr><th>Specific Space Heating Demand</th><td>' + picked3DtileFeature.getProperty('nrg_epc_primaryEnergyDemandValue_s1') + ' ' + 'kWh/m²*yr' + '</td></tr>' +
				'<tr><th>Domestic Hot Water Demand</th><td>' + picked3DtileFeature.getProperty('nrg_dhwDemandYear') + ' ' + 'kWh*yr' + '</td></tr>' +
				'<tr><th>Electricity Domestic Hot Water Demand</th><td>' + picked3DtileFeature.getProperty('nrg_electricityDemandYear') + ' ' + 'kWh*yr' + '</td></tr>' +
				'</tbody></table>';

            console.log(picked3DtileFeature.getProperty('SemanticType'));}
			
			
			else if (picked3DtileFeature.getProperty('SemanticType') === "RoofSurface") {
                
			
            var featureName = "Meidling 3D Viewer - Roof Surface";
            selectedEntity.name = featureName;
            selectedEntity.description = 'Loading <div class="cesium-infoBox-loading"></div>';

            viewer.selectedEntity = selectedEntity;
            selectedEntity.description =
                '<table class="cesium-infoBox-defaultTable"><tbody>' +
                '<tr><th>Building ID</th><td>' + picked3DtileFeature.getProperty('gml_id') + '</td></tr>' +
				'<tr><th>Building Parent ID</th><td>' + picked3DtileFeature.getProperty('gml_parent_id') + '</td></tr>' +
				'<tr><th>Roof Type</th><td>' + picked3DtileFeature.getProperty('citygml_roof_type') + '</td></tr>' +
				'<tr><th>Roof Area </th><td>' + picked3DtileFeature.getProperty('roofArea') + ' ' + 'm²' + '</td></tr>' +
            	'<tr><th>Photovoltaic Potential</th><td>' + picked3DtileFeature.getProperty('PV_yield') + ' ' + 'MWh/yr' + '</td></tr>' +
				'</tbody></table>';

            console.log(picked3DtileFeature.getProperty('SemanticType'));}
			
			else if (picked3DtileFeature.getProperty('SemanticType') === "LandUse") {
                
			
            var featureName = "Meidling 3D Viewer - LandUse";
            selectedEntity.name = featureName;
            selectedEntity.description = 'Loading <div class="cesium-infoBox-loading"></div>';

            viewer.selectedEntity = selectedEntity;
            selectedEntity.description =
                '<table class="cesium-infoBox-defaultTable"><tbody>' +
                '<tr><th>LandUse ID</th><td>' + picked3DtileFeature.getProperty('gml_id') + '</td></tr>' +
                '<tr><th>LandUse Class</th><td>' + picked3DtileFeature.getProperty('NUTZUNG_LE') + '</td></tr>' +
                '<tr><th>LandUse Function</th><td>' + picked3DtileFeature.getProperty('NUTZUNG_L0') + '</td></tr>' +
                '<tr><th>LandUse Usage</th><td>' + picked3DtileFeature.getProperty('NUTZUNG_L1') + '</td></tr>' +
				'<tr><th>LandUse Area </th><td>' + picked3DtileFeature.getProperty('Shape_Area') + ' ' + 'm²' + '</td></tr>' +
				'</tbody></table>';

            console.log(picked3DtileFeature.getProperty('SemanticType'));}
			
			
			else
				{                	
            var featureName = "Meidling 3D Viewer - Building Installation";
            selectedEntity.name = featureName;
            selectedEntity.description = 'Loading <div class="cesium-infoBox-loading"></div>';

            viewer.selectedEntity = selectedEntity;
            selectedEntity.description =
                 '<table class="cesium-infoBox-defaultTable"><tbody>' +
                '<tr><th>Building ID</th><td>' + picked3DtileFeature.getProperty('gml_id') + '</td></tr>' +
				'<tr><th>Building Parent ID</th><td>' + picked3DtileFeature.getProperty('gml_parent_id') + '</td></tr>' +
				'<tr><th>Installation Area </th><td>' + picked3DtileFeature.getProperty('area') + ' ' + 'm²' + '</td></tr>' +
				'</tbody></table>';

            console.log(picked3DtileFeature.getProperty('SemanticType'));}
			
			var arrow = document.getElementById('arrow');
		var arrowPosition = 10 + ((Number(picked3DtileFeature.getProperty('nrg_epc_primaryEnergyDemandValue_s1')) / 250) * 465);
		if (Number(picked3DtileFeature.getProperty('nrg_epc_primaryEnergyDemandValue_s1')) >= 250) {
			arrowPosition = 465;
		}
		console.log("Width: " + arrow.style.width);
		arrow.style.left = arrowPosition + "px";
		console.log("position left: : " + 10 + ((Number(picked3DtileFeature.getProperty('nrg_epc_primaryEnergyDemandValue_s1')) / 250) * 100) * 465 + "px");
		arrow.style.visibility = 'visible';
		}
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
}

active3DTilePicker();