// $scope, $element, $attrs, $injector, $sce, $timeout, $http, $ionicPopup, and $ionicPopover services are available
//======================================
const USED_MODEL_WDG='model-1'
//
// highlighting function. Inputs are the selected part and a boolean for hilite
$scope.hilite = function (items, hilite,mod ) {

  //
  //iterate over each item that is used as an imported variable for the function using .forEach to look at each value that comes in the items input
  items.forEach(function(item) {

    //
    //set the properties of the TML 3D Renderer to highlight the selected item using a TML Text shader. "green" is the name of the script for the TML Text.
    tml3dRenderer.setProperties(mod+"-"+item, hilite === true ? { shader: "green", hidden: false, opacity: 0.9, phantom: false, decal: true }
                                                      : { shader: "", hidden: false, opacity: 1.0, phantom: false, decal: false });
$scope.$applyAsync()
  }) //foreach end

} //hilite function end

 

angular.element(document).ready(function () {
$timeout( ()=>{  
                         $scope.setWidgetProp('3DContainer-1','enabletrackingevents',true);
                          $scope.eyepos=[];
                          $scope.eyedir=[];
                          $scope.eyeup =[];
                         $scope.scale= $scope.app.view['Home'].wdg[ USED_MODEL_WDG]['scale']
                   console.warn("$scope.scale="+$scope.scale)
               
                           $rootScope.$on('tracking', function( tracker,fargs  )             {
    
                            for(var i=0; i<fargs.position.length; i++)
                                 {  $scope.eyepos.push(fargs.position[i])
                                    $scope.eyedir.push(fargs.gaze[i]);
	                                $scope.eyeup.push(fargs.up [i]);	  }
                                })
                         $scope.$applyAsync();
                          }, 500);
})
//-----------------------------------------------------------

//-----------------------------------------------------------

$scope.$on('userpick', function (event, targetName, targetType, eventData) {

  //Look at model and see if it has metadata. If it does, then execute the below code and create an object called metadata
  PTC.Metadata.fromId(targetName)
              .then  ( (metadata) => {  // variable to pull the value for the occurrence property in the eventData JSON object from the model. Create variable for the currently selected part
  
                                                   var pathId = JSON.parse(eventData).occurrence
                                                   $scope.currentSelection = targetName + "-" + pathId; /********/ console.warn("pathId::="+pathId);  // set welding = true until it is turned false
                                                    let pathIds=[]; pathIds.push(pathId);
                                                   $scope.hilite( pathIds,true, targetName);// the same as USED_MODEL_WDG
                                                   $timeout(()=>{$scope.hilite( pathIds,false, USED_MODEL_WDG)},500) //seleciton deactivate after 5 sec's
                                                   
                                                    let position = JSON.parse(eventData).position
                                                    let normal= JSON.parse(eventData).normal
                                                    console.warn("postion:");console.warn(position)
    
                                                   $scope.setWidgetProp('model-2','x',position[0] +normal[0]*0.08 );
                                                   $scope.setWidgetProp('model-2','y',position[1]+normal[1]*0.08 )
                                                   $scope.setWidgetProp('model-2','z',position[2] +normal[2]*0.08 )
                                                   //----------------------------------------------------------------
                                                   $scope.setWidgetProp('3DLabel-1','x',position[0] +($scope.eyepos[0]-position[0] )*0.1 );
                                                   $scope.setWidgetProp('3DLabel-1','y',position[1] +($scope.eyepos[1]-position[1] )*0.1  )
                                                   $scope.setWidgetProp('3DLabel-1','z',position[2] +($scope.eyepos[2]-position[2] )*0.1 )   
                                                   $scope.setWidgetProp('3DLabel-1','text'," <  "+position[0].toFixed(4)+" , "+position[1].toFixed(4)+" , "+position[2].toFixed(4)+" > " )
    
    //============================
   //$scope.scale1=1.0/  $scope.scale
                                        
                                       let shaderString= 'spherical_cut;clipCenterX f '+(position[0] ).toFixed(4)
                                                                                              +';clipCenterY f '+(position[1] ).toFixed(4)+';clipCenterZ f '
                                                                                              +(position[2]).toFixed(4)+';clipRadius f 0.05';
    
                                                        //$scope.app.view['Home'].wdg[ USED_MODEL_WDG]
                                         $scope.setWidgetProp(USED_MODEL_WDG ,'shader',shaderString);  $scope.$applyAsync();
    
                                 //  $scope.setWidgetProp(USED_MODEL_WDG ,'shader', 'xray; r f 0.882; g f 0; b f 1; a f 0.5');
    
          /*                      $scope.view.wdg[USED_MODEL_WDG].shader = 'planar_cut; clipCenterX f '+(position[0]/ $scope.scale).toFixed(4)
                                                                                              +'; clipCenterY f  '+(position[1]/ $scope.scale).toFixed(4)+'; clipCenterZ f  ' +(position[2]/ $scope.scale).toFixed(4)
                                                                                              +';clipAxisX f '+(normal[0]).toFixed(4)
                                                                                              +'; clipAxisY f  '+(normal[1]).toFixed(4)+'; clipAxisZ f  ' +(normal[2]).toFixed(4)+';clipLineWidth f 0.003;'*/
    
/*                                         $scope.app.view['Home'].wdg[USED_MODEL_WDG 'shaderMdlItem'] .shader = 'spherical_cut; clipCenterX f '+(position[0]).toFixed(4)
                                                                                              +'; clipCenterY f  '+(position[1]).toFixed(4)+'; clipCenterZ f  '
                                                                                              +(position[2]).toFixed(4)+';clipRadius f 0.5'; */   
                                       console.warn("shader set ::>"+$scope.app.view['Home'].wdg[USED_MODEL_WDG].shader)

                                               $scope.$applyAsync();
                                               $timeout(()=>{  $scope.setWidgetProp(USED_MODEL_WDG ,'shader','' ); $scope.$applyAsync(); },500) //seleciton deactivate after 5 sec's
  //====================  
                                                    //----------------------------------------------------------------   
                                                   $scope.setWidgetProp('label-4','text'," < "+position[0].toFixed(4)+","+position[1].toFixed(4)+","+position[2].toFixed(4)+"> " )
                                                    //----------------------------------------------------------------                                                 
                                                   
                                                   $scope.$applyAsync();
                                     
                                    
    
                        //    
                     
                  $scope.target = targetName;
              
    
                //
                // call the getPriceAvailability ThingWorx service based on partNumber
             // twx.app.fn.triggerDataService('shoppingThing_303', 'getPriceAvailability', {pid: $scope.meta.partNumber})
              //  twx.app.fn.triggerDataService('shoppingThing_303', 'getPriceAvailabilityDataTable', {pid: $scope.meta.partNumber}) 
                  }) //end brackets for PTC API and .then

  //catch statement if the promise of having a part with metadata is not met
  .catch( (err) => { console.log('metadata extraction failed with reason : ' +err) })

}) //end brackets for userpick function. Will continue to move throughout code

//=====================================
$scope.app.isIOS=function() { 
    if(!window.twx.app.isPreview()) // is not in Preview
       if(ionic.Platform.isIOS()) //and is NOT called on IOS = means Android mode detected
         return true;
   return false; }
//======================================
$scope.app.isPreview=function() { 
    if(twx.app.isPreview()) // is in Preview
         return true;
   return false; }
//======================================
$scope.app.isAndroid=function() { 
    if(!window.twx.app.isPreview()) // is not in Preview
      if(/android/i.test(navigator.userAgent || navigator.vendor || window.opera) ) // is Android
         return true;
   return false; }
//======================================
$scope.app.isWinPhone=function() { 
    if(!window.twx.app.isPreview()) // is not in Preview
      if(/windows phone/i.test(navigator.userAgent || navigator.vendor || window.opera) ) // is Android
         return true;
   return false; }
//======================================
$scope.app.isWindow=function() { 
    if(!window.twx.app.isPreview()) // is not in Preview
       if( navigator.platform.indexOf("Win32") >- 1) // is this WindowsPhone
         return true;
     return false; }
//========================================
let DEBUG=true


//=======================================================================

//######################################
//angular.element(document).ready(function () {
$scope.$on('$ionicView.afterEnter', function() {
  console.warn($scope)
  console.warn($rootScope)
   // start test code below 
   //$scope.setItemsList();
   //$scope.Test();
if($scope.app.isPreview()) 
 {
    twx.app.fn.addSnackbarMessage("PREVIEW MODE","twLogo"); 
  $scope.setWidgetProp('label-3',  'text',  "called in Preview Mode");
 //=========================================================
 
  
// here end teste code 
 }
else if($scope.app.isIOS()){
  	$scope.setWidgetProp('label-3',  'text',  "called on IOS Device");
  twx.app.fn.addSnackbarMessage("called on IOS Device","twLogo"); }
else if($scope.app.isAndroid()) {
  $scope.setWidgetProp('label-3',  'text',  "called on Android Device");
  twx.app.fn.addSnackbarMessage("called on Android Device","twLogo"); }
else if($scope.app.isWindow()) {
  $scope.setWidgetProp('label-3',  'text',  "called on Window Plattform");
  alert("called on Windows Phone Device"); }

  })
  
  //===========================================================
//////=========================================================
function hasWdgProp(widget,property)
{
 	for (wp in widget)	{
            //console.log("property="+property+" | wp="+wp);
           if(wp==property) return true;
           else continue;
						}
}


