<commit_before><html   ng-app="myApp" ng-controller="AppCtrl">
<head>
    <title>Ptolemy - The Network Cartographer</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-animate.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-aria.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angular_material/0.9.4/angular-material.min.js"></script>
  <!-- JQuery Min for File Upload and Reading content of file -->
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  <!-- Script for Editable table and Text Area -->
  <script src="js/xeditable.js"></script>
  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/0.9.4/angular-material.min.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=RobotoDraft:300,400,500,700,400italic">


  <!--  Favicon -->
  <link rel="apple-touch-icon" sizes="57x57" href="img/icons/favicon/apple-icon-57x57.png">
  <link rel="apple-touch-icon" sizes="60x60" href="img/icons/favicon/apple-icon-60x60.png">
  <link rel="apple-touch-icon" sizes="72x72" href="img/icons/favicon/apple-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="76x76" href="img/icons/favicon/apple-icon-76x76.png">
  <link rel="apple-touch-icon" sizes="114x114" href="img/icons/favicon/apple-icon-114x114.png">
  <link rel="apple-touch-icon" sizes="120x120" href="img/icons/favicon/apple-icon-120x120.png">
  <link rel="apple-touch-icon" sizes="144x144" href="img/icons/favicon/apple-icon-144x144.png">
  <link rel="apple-touch-icon" sizes="152x152" href="img/icons/favicon/apple-icon-152x152.png">
  <link rel="apple-touch-icon" sizes="180x180" href="img/icons/favicon/apple-icon-180x180.png">
  <link rel="icon" type="image/png" sizes="192x192"  href="img/icons/favicon/android-icon-192x192.png">
  <link rel="icon" type="image/png" sizes="32x32" href="img/icons/favicon/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="96x96" href="img/icons/favicon/favicon-96x96.png">
  <link rel="icon" type="image/png" sizes="16x16" href="img/icons/favicon/favicon-16x16.png">
  <link rel="manifest" href="/manifest.json">
  <meta name="msapplication-TileColor" content="#ffffff">
  <meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
  <meta name="theme-color" content="#ffffff">
  <!-- Favicon ends -->

  <style type="text/css">
  .editable-error{
    color: red
  }
  pre {
    white-space: pre-wrap;       /* CSS 3 */
    white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
    white-space: -pre-wrap;      /* Opera 4-6 */
    white-space: -o-pre-wrap;    /* Opera 7 */
    word-wrap: break-word;       /* Internet Explorer 5.5+ */
  }
  </style>

</head>
<body>
<div ng-controller="AppCtrl" layout="column">
  <section layout="row" flex>
    <md-sidenav class="md-sidenav-left md-whiteframe-z2" md-component-id="left" md-is-locked-open="sidebar == true">
      <md-content layout-padding layout="column">
        <img ng-src="img/icons/logo.png" alt="Ptolemy - The Network Cartographer" style="padding-left:40px" layout-align="center center">
        <!-- <img ng-src="img/icons/glyphicons_collapse.png" alt="Hide" style="padding-left:40px" layout-align="center center"> -->
      </md-content>
      <md-button class="md-primary" layout-align="bottom right" ng-click="hideSideNav()" ng-show="sidebar == true"> Hide </md-button>
    </md-sidenav>
    <md-button class="md-primary" layout-align="bottom right" ng-click="hideSideNav()" ng-show="sidebar == false"> Hide </md-button>
    <md-content flex layout-padding>

    	<md-toolbar class="md-theme-indigo">
        	<h1 class="md-toolbar-tools">Home</h1>
      	</md-toolbar>

      <!-- Page 1 : Choose between Existing Template or download a Sample Template button -->

      <div layout="column" layout-fill layout-align="top center" ng-show="pageOneVisible">
        <md-card>
              <md-card-content>
                <h2 class="md-title">Configuration</h2>
                <md-switch class="md-primary" md-no-ink ng-model="templateSwitch" ng-change="onTemplateSwitchChange(templateSwitch)">
                Develop using Existing Template</md-switch>
                <span>
                <label for="file-input" style="margin-left:20px">Browse Template</label>  
                <input id="file-input" style="margin-left:10px" type="file" accept=".ptpl" ng-disabled="isTemplateDisabled" on-read-file="loadTemplate($fileContent)">

                <md-button class="md-raised md-primary" ng-click="downloadSampleTemplate()">Download Sample Template</md-button>
                <a href="downloadUrl" id="fileDownloadLink" ng-hide="true"></a>
                </span>
                <div ng-show="templateUploaded == true">
                  <h3>Template</h3>
                    <md-checkbox md-no-ink ng-init="showPasswords == false" class="md-primary" ng-model="showPasswords" aria-label="Show Password" ng-true-value="true" ng-false-value="false"> Show Passwords</md-checkbox>
                    <pre ng-show="showPasswords == true">{{ template }}</pre>
                    <pre ng-show="showPasswords == false">{{ passwordEncodedTemplate }}</pre>
                  <!-- </span> -->

                </div>


                </md-card-content>
          </md-card>
          <section layout="row" layout-sm="column" layout-align="center center">
              <md-button class="md-raised md-primary" ng-click="PageTwo()"> Build New Configuration </md-button>
              <md-button class="md-raised md-primary" ng-click="generateGraphFromTemplate(template, $event)"> Generate Graph 
              <md-tooltip> Choose an existing template to generate graph directly or build a new configuration.
              </md-tooltip>
              </md-button>
          </section> 
          <!-- <a id="fileDownloadLink" ng-hide="true" ng-href="downloadUrl" /> -->
      </div>

      <!-- End of Page 1 -->

      <!-- Page 2 - Configuration : Choose Global Credentials -->
      <div layout="column" layout-fill layout-align="top center"  ng-show="pageTwoVisible">
       <md-card>
              <md-card-content>
                <h2 class="md-title">Configuration</h2>
                <md-checkbox md-no-ink class="md-primary" ng-model="global_credentials" aria-label="Use Global User Credentials">
                  Use Global User Credentials
                </md-checkbox>


                <div ng-show="global_credentials == true">

                <!-- Username and Password If User Credentials is chosen -->
                <md-content layout-padding layout="row" layout-sm="column">
                <!-- ng-show="userCredentials" -->
                    <label style="margin-top:10px">Username</label>
                    <input id="username" style="height:30px;margin-top:5px;margin-left:5px" ng-model="global_user.username">
                    <label style="margin-top:10px;margin-left:10px">Password</label>
                    <input id="password" style="height:30px;margin-top:5px;margin-left:5px" ng-model="global_user.password" type="{{passwordField}}">
                    <md-checkbox md-no-ink class="md-primary" ng-model="passwordField" aria-label="Show Password" id="show_password" ng-true-value="'text'" ng-false-value="'password'"> Show Password</md-checkbox>
                </md-content>

                </div>


                 <!-- Settings for Log Generation -->
                <md-content layout-padding layout="row" layout-sm="column" > 

                    <div layout="row">
                      <div flex="50" flex-md="100" layout="column">
                        <fieldset class="standard" flex>
                          <legend>Output Formats</legend>
                          <div layout="row" layout-wrap>
                           <div flex="50" ng-repeat="item in output_formats">
                             <md-checkbox md-no-ink class="md-primary" flex="50" ng-checked="format_exists(item, selected_output_formats)" ng-click="toggle_output_formats(item, selected_output_formats)" aria-label="item">
                                {{ item }}
                            </md-checkbox>
                             <!-- <md-checkbox md-no-ink class="md-primary" ng-checked="format.dot == true" ng-model="format.dot" aria-label="DOT" flex="50" ng-value="DOT">
                              DOT
                             </md-checkbox>
                             </div>
                              <div class="standard" flex="50">
                             <md-checkbox md-no-ink class="md-primary" ng-checked="format.json == true" ng-model="format.json" aria-label="JSON" flex="50" ng-value="JSON">
                                JSON
                             </md-checkbox>
                             </div>
                              <div class="standard" flex="50">
                             <md-checkbox md-no-ink class="md-primary" ng-checked="format.svg == true" ng-model="format.svg" aria-label="SVG" flex="50" ng-value="SVG">
                                SVG
                             </md-checkbox>
                             </div>
                              <div class="standard" flex="50">
                             <md-checkbox md-no-ink class="md-primary" ng-checked="format.pdf == true" ng-model="format.pdf" aria-label="PDF" flex="50" ng-value="PDF">
                                PDF
                             </md-checkbox>
                             </div>
                              <div class="standard" flex="50">
                             <md-checkbox md-no-ink class="md-primary" ng-checked="format.png == true" ng-model="format.png" aria-label="PNG" flex="50" ng-value="PNG">
                                PNG
                             </md-checkbox> -->
                           </div>
                          </div>
                        </fieldset>
                      </div>

                      <div flex="50" flex-md="100" layout="column">
                        <fieldset class="standard" flex>
                          <legend>Logs</legend>
                          <div layout="row" layout-wrap>
                            <md-radio-group ng-model="log_config" class="md-primary">
                              <md-radio-button value="global_log" class="md-primary">Generate Global Logs</md-radio-button>
                              <md-radio-button value="device"> Generate Logs Per Device </md-radio-button>
                            </md-radio-group>
                            <!-- <md-checkbox md-no-ink class="md-primary" ng-model="log_config.global_log" aria-label="Generate Global Logs" >
                            Generate Global Logs
                           </md-checkbox>
                           <md-checkbox md-no-ink class="md-primary" ng-model="log_config.device" aria-label="Generate Logs Per Device">
                            Generate Logs Per Device
                           </md-checkbox> -->
                           
                          </div>
                        </fieldset>
                      </div>
                    </div>

                </md-content>
      
              </md-card-content>
        </md-card>

        <section layout="row" layout-sm="column" layout-align="center center">
            <md-button class="md-raised md-primary" ng-click="PageOne()" > Back </md-button>
            <md-button class="md-raised md-primary" ng-click="PageThree($event)" > Next </md-button>
           <div class="label" style="visibility: hidden">Raised</div>
        </section> 
      </div>
      <!-- End of Page 2 -->

      <!-- Page 3 - Configuration : Upload CSV and Connection Table -->
      <div layout="column" layout-fill layout-align="top center" ng-show="pageThreeVisible">
       <md-card>
              <md-card-content>
                <h2 class="md-title">Configuration</h2>

                    <!-- Browse CSV File -->
                    <md-content layout-padding layout="row" layout-sm="column" > 
                    <!-- ng-show="sshCredentials" -->
                        <label style="margin-bottom:20px">Connection Details</label>
                        <input type="file" id="connection_details" accept=".csv" style="margin-bottom:20px;margin-left:10px" on-read-file="loadConnectionDetails($fileContent)">
                    </md-content>


              		  <form editable-form name="tableform" onaftersave="saveTable()" oncancel="cancel()">


            			    <!-- table -->
            			    <table class="table table-bordered table-hover table-condensed">
            			      <tr style="font-weight: bold">
            			        <td style="width:40%">Hostname</td>
            			        <td style="width:25%">Username</td>
            			        <td style="width:25%">Password</td>
                          <td style="width:10%">Port</td>
            			        <td style="width:20%"><span ng-show="tableform.$visible">Action</span></td>
            			      </tr>
            			      <tr ng-repeat="device in connectionDetails | filter : filterConnections">
            			        <td>
            			          <!-- editable username (text with validation) -->
            			          <span editable-text="device.hostname" e-form="tableform" ng-show="editableTable == false" onbeforesave="checkHostName($data)">
            			            {{ device.hostname }}
            			          </span>
            			        </td>
            			        <td>
            			          <!-- editable status (select-local) -->
            			          <span editable-text="device.username" e-form="tableform" ng-show="editableTable == false" onbeforesave="checkUserName($data)">
            			            {{ device.username }}
            			          </span>
            			        </td>
            			        <td>
            			          <!-- editable group (select-remote) -->
            			          <span editable-password="<PASSWORD>" e-form="tableform" ng-show="editableTable == false" onbeforesave="checkPassword($data)">
            			            <input type="password" name="lname" disabled value="{{ device.password }}">
            			          </span>
            			        </td>
                          <td>
                            <!-- editable group (select-remote) -->
                            <span editable-text="device.port" e-form="tableform" ng-show="editableTable == false">
                              {{ device.port }}
                            </span>
                          </td>
            			        <td><md-button class="md-raised md-warn" ng-show="tableform.$visible" ng-click="deleteConnectionDetail(device.hostname)">Delete</md-button></td>
            			      </tr>
            			    </table>

            			    <!-- buttons -->
            			    <div class="btn-edit">
            			      <md-button  type="button" class="md-raised md-primary" ng-show="!tableform.$visible" ng-click="tableform.$show()">
            			        edit
            			      </md-button >
            			    </div>
            			    <div class="btn-form" ng-show="tableform.$visible">
            			      <md-button  type="button" ng-disabled="tableform.$waiting" ng-click="addNewConnectionDetail()" class="md-raised md-primary">add device</md-button >
            			      <md-button  type="submit" ng-disabled="tableform.$waiting" class="md-raised md-primary">confirm</md-button >
            			      <md-button  type="button" ng-disabled="tableform.$waiting" ng-click="tableform.$cancel()" class="md-raised md-primary">cancel</md-button >
            			    </div> 
        			    
        			  </form>

                </md-card-content>
          </md-card>

          <section layout="row" layout-sm="column" layout-align="center center">
              <md-button class="md-raised md-primary" ng-click="PageTwo()" > Back </md-button>
              <md-button class="md-raised md-primary" ng-click="PageFour($event)" > Generate Graph </md-button>
             <div class="label" style="visibility: hidden">Raised</div>
          </section> 

      </div>
      <!-- End of Page 3 -->


      <!-- Page 4 - Content showing Generated graph and other options -->
      <div layout="column" layout-fill layout-align="top center" ng-show="pageFourVisible">
       <md-card>
              <md-card-content>
                <div>
                  <h1 class="md-title">Network Topology</h1>
                  <span>
                  <label>View As</label>
                  <md-select placeholder="Content Type" ng-model="view_format">
                    <md-option ng-repeat="view_format in selected_output_formats" value="{{view_format}}">{{view_format}}</md-option>
                  </md-select>
                  <md-button class="md-raised md-primary" ng-click="" > Download </md-button>
                  <md-button class="md-raised md-primary" ng-click="" > Download All Formats </md-button>
                  <md-button class="md-raised md-primary" ng-click="" > Save Configuration as Template </md-button>
                  </span>

                  <!-- View to Indicate that work is in progress -->
                  <div id="loading_div" ng-show="loading == true">
                      <h4>This might take a while. Please wait...</h4>
                      <div layout="row" layout-sm="column" layout-align="space-around">
                        <md-progress-circular md-mode="indeterminate"></md-progress-circular>
                      </div>
                  </div>
                  <!-- View to Show the results -->
                  <div id='content_view' ng-show="loading == false" style="overflow:auto;height:60%;width:100%;margin-top:20px;margin-bottom:10px">
                  </div>
                </div>
              </md-card-content>
          </md-card>

          <section layout="row" layout-sm="column" layout-align="center center">
              <md-button class="md-raised md-primary" ng-click="PageThree()" > Back </md-button>
              <md-button class="md-raised md-primary" ng-click="PageOne()" > Start Again </md-button>
             <div class="label" style="visibility: hidden">Raised</div>
          </section> 

      </div>
      <!-- End of Page 4 -->


     <div flex></div>

    </md-content>


    <!-- Right Side Navigator -->
    <!-- <md-sidenav class="md-sidenav-right md-whiteframe-z2" md-component-id="right">
      <md-toolbar class="md-theme-light">
        <h1 class="md-toolbar-tools">Sidenav Right</h1>
      </md-toolbar>
      <md-content layout-padding>
        <form>
          <md-input-container>
            <label for="testInput">Test input</label>
            <input type="text" id="testInput"
                   ng-model="data" md-sidenav-focus>
          </md-input-container>
        </form>
        <md-button ng-click="close()" class="md-primary">
          Close Sidenav Right
        </md-button>
      </md-content>
    </md-sidenav> -->
    <!-- End of Right side navigator -->

  </section>
</div>


<script>
var app = angular.module('myApp', ['ngMaterial','xeditable']);
app.controller('AppCtrl', function ($scope, $timeout, $mdSidenav, $mdUtil, $mdDialog, $log, $filter, $http, $q) {

  $scope.isTemplateDisabled = true;
  $scope.global_credentials = false;
  $scope.passwordField = "password";

  $scope.editableTable = false;
  $scope.connectionDetailsUploaded = false;
  $scope.templateUploaded = false;
  $scope.templateEditable = false;
  $scope.showPasswords = false;

  $scope.configuration = [];

  $scope.connectionDetails = [];

	$scope.pageOneVisible = true;
	$scope.pageTwoVisible = false;
	$scope.pageThreeVisible = false;
  $scope.sidebar = true;
  $scope.log_config = "global_log";
  $scope.output_formats = ["DOT","JSON","SVG","PDF","PNG"];
  $scope.selected_output_formats = ["DOT","JSON","SVG","PDF","PNG"];


  $scope.toggle_output_formats = function (item, list) {
        var idx = list.indexOf(item);
        if (idx > -1) list.splice(idx, 1);
        else list.push(item);
  };

  $scope.format_exists = function (item, list) {
        return list.indexOf(item) > -1;
  };

  // $scope.format.dot = true;
  // $scope.format.json = true;
  // $scope.format.svg = true;
  // $scope.format.pdf = true;
  // $scope.format.png = true;

  // $scope.log_config.global_log = true;

  $scope.hideSideNav = function () {
   $mdSidenav('left').close();
   $scope.sidebar = !$scope.sidebar;
  }

	$scope.PageOne = function () {
		$scope.pageOneVisible = true;
		$scope.pageTwoVisible = false;
		$scope.pageThreeVisible = false;
    $scope.pageFourVisible = false;
    }

	$scope.PageTwo = function () {
		$scope.pageOneVisible = false;
		$scope.pageTwoVisible = true;
		$scope.pageThreeVisible = false;
    $scope.pageFourVisible = false;

    // Clear all the configuration since it will be updated on press of next
    $scope.configuration = [];
    $scope.logs = [];

    var request = $http({
                    method: "POST",
                    url: "/ptolemy",
                    data: $scope.configuration
                });
    // Store the data-dump of the FORM scope.
    request.success(
        function( html ) {
            $scope.cfdump = html;
        }
    );

      
		// $http.post("/asd.svg", {file1:$scope.tracediffFile1, file2:$scope.tracediffFile2})
  //     .success(function (response) {
  //       $scope.svgFile = response;

  //       angular.element( document.querySelector( '#svgg' ) ).append($scope.svgFile);
		// $scope.$apply ();
  //     });
    }

	$scope.PageThree = function (ev) {

    //Update the dictionary with configuration details
    // $scope.output_formats = [];
    $scope.logs = [];

    // If Output format is checked, add it to supported formats
    // angular.forEach($scope.format, function(value, key) {
    //   if (value) {
    //     $scope.output_formats.push({'format':key,'name':key.toUpperCase()});
    //   };
    // });

    // If any log type is checked, add it to configuration
    // angular.forEach($scope.log_config, function(value, key) {
    //   if (value) {
    //     $scope.logs.push(key);
    //   };
    // });
    if ($scope.log_config == 'device') {
      $scope.logs = "Device"
    } else {
      $scope.logs = "Global"
    };
    // Validate if Credentials are entered if gloval credentials is checked
    if (($scope.global_credentials && !$scope.global_user) || ($scope.global_credentials && (!$scope.global_user.username || !$scope.global_user.password))) {
      $mdDialog.show(
          $mdDialog.alert()
            .parent(angular.element(document.body))
            .title('Incomplete Credentials')
            .content('Please enter Username and password or uncheck Global User Credentials to proceed.')
            .ariaLabel('Template Upload')
            .ok('OK')
            .targetEvent(ev)
        );
    } else{

        $scope.pageOneVisible = false;
        $scope.pageTwoVisible = false;
        $scope.pageThreeVisible = true;
        $scope.pageFourVisible = false;

        if ($scope.global_credentials) {
          $scope.user_credentials = {
            "username" : $scope.global_user.username,
            "password" : <PASSWORD>
          };
          $scope.configuration.push({
            "Global Credentials" : $scope.user_credentials,
            "Output Formats" : $scope.selected_output_formats,
            "Logs" : $scope.logs,
            "Connection Details": ""
          });
        } else {
          $scope.configuration.push({
            "Global Credentials" : 'None',
            "Output Formats" : $scope.selected_output_formats,
            "Logs" : $scope.logs,
            "Connection Details": ''
          });
        };
        
    };
  }



  $scope.downloadSampleTemplate = function () {

    var request = $http({
                    method: "POST",
                    url: "/download-sample-template",
                });
    // Store the data-dump of the FORM scope.
    request.success(
        function( response ) {
            $scope.downloadUrl = response.data.fileName;

            var fileDownloadLink = document.getElementById("fileDownloadLink");
            fileDownloadLink.target = "_blank"; // Opens the file in a new window.
            fileDownloadLink.click();
            //$scope.resp = response;
            /*
            $scope.svgFile = response;
            
            if svg file do ::
            angular.element( document.querySelector( '#svgg' ) ).append($scope.svgFile);
            $scope.$apply ();

            for pdf it will be something else.
        */
        }
    );

    }


   $scope.generateGraphFromTemplate =  function (template, ev) {
      if ($scope.templateUploaded) {
        $scope.configuration = JSON.parse(template);
        // Fetch the Output Formats from the JSON Dictionary
        formats = $scope.configuration["Output Formats"];
        $scope.selected_output_formats = [];
        for (index=0;index < formats.length; index++){
          $scope.selected_output_formats.push(formats[index].toUpperCase());
        }
        //$scope.output_formats = [{'format':'svg','name':'SVG'},{'format':'pdf','name':'PDF'}]
        $scope.GenerateGraph();
      }
      else {
        $mdDialog.show(
          $mdDialog.alert()
            .parent(angular.element(document.body))
            .title('No template uploaded')
            .content('You will have to choose a template or build a new configuration to proceed.')
            .ariaLabel('Template Upload')
            .ok('OK')
            .targetEvent(ev)
        );
      }
    }


  $scope.checkHostName = function(hostname) {
    if (!hostname) {
      return "Please enter a valid hostname.";
    }
  };

  $scope.checkUserName = function(username) {
    if (!$scope.global_credentials && !username) {
      return "Please enter a valid username.";
    }
  };

  $scope.checkPassword = function(password) {
    if (!$scope.global_credentials && !password) {
      return "Please enter a valid password.";
    }
  };

  $scope.PageFour = function (ev) {
    if($scope.connectionDetailsUploaded || ($scope.connectionDetails && $scope.connectionDetails.length > 0  && $scope.connectionDetails[0]['hostname'])){
      // Push Connection Details to Configuration
      $scope.configuration[0]['Connection Details'] = $scope.connectionDetails;
      // Hack to Send it at a dictionary instead of a list of one element
      $scope.configuration = $scope.configuration[0];
      $scope.GenerateGraph();
    } else {
      $mdDialog.show(
          $mdDialog.alert()
            .parent(angular.element(document.body))
            .title('Device Configuration missing')
            .content('You will have to upload a  file containing device connections or build a connection profile.')
            .ariaLabel('Device Configuration')
            .ok('OK')
            .targetEvent(ev)
        );
    }
  }


  $scope.GenerateGraph = function (){
      $scope.pageOneVisible = false;
      $scope.pageTwoVisible = false;
      $scope.pageThreeVisible = false;
      $scope.pageFourVisible = true;
      $scope.loading = true;

      var request = $http({
                    method: "POST",
                    url: "/pageFour",
                    headers : {
                          'Content-Type' : 'application/json'
                        },
                    data: $scope.configuration
                });
      // Store the data-dump of the FORM scope.
      request.success(
          function( response ) {
              $scope.loading = false;
              // Parse the SVG and change the height 
              // Dirty hack to make the SVG fit the div
              var parser = new DOMParser();
              var svgContent = parser.parseFromString(response,"text/xml");
              svgContent.getElementsByTagName("svg")
              $scope.svgFile = response;
              angular.element( document.querySelector( '#content_view' ) ).append($scope.svgFile);
              $scope.$apply ();
          }
      );
  }
    // var url = "/pageFour";
    // $http.post(url, fd, {
    //     withCredentials : false,
    //     headers : {
    //     'Content-Type' : undefined
    //     }
    //    })
    //    .success(function(data)
    //    {
    //     console.log(data);
    //    })
    //    .error(function(data)
    //    {
    //     console.log(data);
    //    });
    //   }


    // var request = $http({
    //                 method: "POST",
    //                 url: "/pageFour",
    //                 headers : {
    //                        'Content-Type' : 'application/text'
    //                 },
    //                 data: $scope.configuration
    //             });
    // // Store the data-dump of the FORM scope.
    // request.success(
    //     function( reponse ) {
    //         $scope.resp = response;
    //         /*
    //         $scope.svgFile = response;
            
    //         if svg file do ::
    //         angular.element( document.querySelector( '#svgg' ) ).append($scope.svgFile);
    //         $scope.$apply ();

    //         for pdf it will be something else.
    //     */
    //     }
    // );

    // }


  $scope.onTemplateSwitchChange = function(switchValue) {
    $scope.isTemplateDisabled = !switchValue
  }

  $scope.loadConnectionDetails = function($fileContent){
    //Parse the file content and put it into template details
    $scope.connectionDetails = [];
    $scope.fileArray = $fileContent.split("\n");
    // Ignore Line 1 since it will always contain the Headers
    for (index = 1; index < $scope.fileArray.length; index++) {
      var tempArr = $scope.fileArray[index].split(",")
      //Run another for loop to build the configuration
      if (tempArr[0] && tempArr[1]) {
        $scope.connectionDetails.push({
          hostname: tempArr[0],
          username: tempArr[1],
          password: tempArr[2],
          path: tempArr[3],
          port: tempArr[4]
        });
      };
    }
    $scope.connectionDetailsUploaded = true;
  };

  $scope.loadTemplate = function($fileContent){
    //Parse the file content and put it into connection details
    $scope.template = $fileContent;
    $scope.passwordEncodedTemplate = JSON.parse($fileContent);
    $scope.passwordEncodedTemplate["Global Credentials"]["password"] = "***";
    for (var i = 0; i < $scope.passwordEncodedTemplate["Connection Details"].length; i++) {
      $scope.passwordEncodedTemplate["Connection Details"]["password"] = "***";
    };
    $scope.templateString = JSON.stringify($scope.template, null, "\t");
    $scope.passwordEncodedTemplateString = JSON.stringify($scope.passwordEncodedTemplateString, null, "\t");
    $scope.templateUploaded = true;
  };

  // $scope.showContent = function($fileContent){
  //       $scope.content = $fileContent;
  // };
  

  // $scope.connectionDetails = [
  // {hostname: 'cdbu-sol-vcf-5100-24q-01.dcbg.juniper.net', username: 'root', password: '<PASSWORD>', path: '', port: ''},  
  // {hostname: 'cdbu-sol-vcf-5100-24q-02.dcbg.juniper.net', username: 'root', password: '<PASSWORD>', path: '', port: ''},  
  // {hostname: 'cdbu-sol-vcf-5100-24q-03.dcbg.juniper.net', username: 'root', password: '<PASSWORD>', path: '', port: ''},   
  // {hostname: 'cdbu-sol-vcf-5100-24q-04.dcbg.juniper.net', username: 'root', password: '<PASSWORD>', path: '', port: ''},  
  // {hostname: 'cdbu-sol-vcf-5100-48s-01.dcbg.juniper.net', username: 'root', password: '<PASSWORD>', path: '', port: ''},  
  // {hostname: 'cdbu-sol-vcf-5100-48s-02.dcbg.juniper.net', username: 'root', password: '<PASSWORD>', path: '', port: ''},    
  // {hostname: 'cdbu-sol-vcf-5100-48s-03.dcbg.juniper.net', username: 'root', password: '<PASSWORD>', path: '', port: ''},  
  // {hostname: 'cdbu-sol-vcf-5100-48s-04.dcbg.juniper.net', username: 'root', password: '<PASSWORD>', path: '', port: ''},   
  // {hostname: 'cdbu-sol-vcf-5100-48s-05.dcbg.juniper.net', username: 'root', password: '<PASSWORD>', path: '', port: ''},   
  // {hostname: 'cdbu-sol-vcf-5100-48s-06.dcbg.juniper.net', username: 'root', password: '<PASSWORD>', path: '', port: ''}
  // ];

  // filter users to show
  $scope.filterConnections = function(device) {
    return device.isDeleted !== true;
  };

  // mark device as deleted
  $scope.deleteConnectionDetail = function(hostname) {
    var filtered = $filter('filter')($scope.connectionDetails, {hostname: hostname});
    if (filtered.length) {
      filtered[0].isDeleted = true;
    }
  };

  // add device
  $scope.addNewConnectionDetail = function() {
    $scope.connectionDetails.push({
      hostname: '', 
      username: '', 
      password: '', 
      path: '', 
      port: '',
      isNew: true
    });
  };

  // cancel all changes
  $scope.cancel = function() {
    for (var i = $scope.connectionDetails.length; i--;) {
      var device = $scope.connectionDetails[i];    
      // undelete
      if (device.isDeleted) {
        delete device.isDeleted;
      }
      // remove new 
      if (device.isNew) {
        $scope.connectionDetails.splice(i, 1);
      }      
    };

    // for (var i = $scope.users.length; i--;) {
    //   var user = $scope.users[i];    
    //   // undelete
    //   if (user.isDeleted) {
    //     delete user.isDeleted;
    //   }
    //   // remove new 
    //   if (user.isNew) {
    //     $scope.users.splice(i, 1);
    //   }      
    // };
  };

  // save edits
  $scope.saveTable = function() {
    var results = [];
    for (var i = $scope.connectionDetails.length; i--;) {
      var device = $scope.connectionDetails[i];
      // actually delete user
      if (device.isDeleted) {
        $scope.connectionDetails.splice(i, 1);
      }
      // mark as not new 
      if (device.isNew) {
        device.isNew = false;
      }

      // send on server
      //results.push($http.post('/saveUser', device));      <commit_msg>Removing unwanted code and commented code<commit_after><html   ng-app="myApp" ng-controller="AppCtrl">
<head>
    <title>Ptolemy - The Network Cartographer</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-animate.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-aria.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angular_material/0.9.4/angular-material.min.js"></script>
  <!-- JQuery Min for File Upload and Reading content of file -->
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  <!-- Script for Editable table and Text Area -->
  <script src="js/xeditable.js"></script>
  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/0.9.4/angular-material.min.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=RobotoDraft:300,400,500,700,400italic">


  <!--  Favicon -->
  <link rel="apple-touch-icon" sizes="57x57" href="img/icons/favicon/apple-icon-57x57.png">
  <link rel="apple-touch-icon" sizes="60x60" href="img/icons/favicon/apple-icon-60x60.png">
  <link rel="apple-touch-icon" sizes="72x72" href="img/icons/favicon/apple-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="76x76" href="img/icons/favicon/apple-icon-76x76.png">
  <link rel="apple-touch-icon" sizes="114x114" href="img/icons/favicon/apple-icon-114x114.png">
  <link rel="apple-touch-icon" sizes="120x120" href="img/icons/favicon/apple-icon-120x120.png">
  <link rel="apple-touch-icon" sizes="144x144" href="img/icons/favicon/apple-icon-144x144.png">
  <link rel="apple-touch-icon" sizes="152x152" href="img/icons/favicon/apple-icon-152x152.png">
  <link rel="apple-touch-icon" sizes="180x180" href="img/icons/favicon/apple-icon-180x180.png">
  <link rel="icon" type="image/png" sizes="192x192"  href="img/icons/favicon/android-icon-192x192.png">
  <link rel="icon" type="image/png" sizes="32x32" href="img/icons/favicon/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="96x96" href="img/icons/favicon/favicon-96x96.png">
  <link rel="icon" type="image/png" sizes="16x16" href="img/icons/favicon/favicon-16x16.png">
  <link rel="manifest" href="/manifest.json">
  <meta name="msapplication-TileColor" content="#ffffff">
  <meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
  <meta name="theme-color" content="#ffffff">
  <!-- Favicon ends -->

  <style type="text/css">
  .editable-error{
    color: red
  }
  pre {
    white-space: pre-wrap;       /* CSS 3 */
    white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
    white-space: -pre-wrap;      /* Opera 4-6 */
    white-space: -o-pre-wrap;    /* Opera 7 */
    word-wrap: break-word;       /* Internet Explorer 5.5+ */
  }
  </style>

</head>
<body>
<div ng-controller="AppCtrl" layout="column">
  <section layout="row" flex>
    <md-sidenav class="md-sidenav-left md-whiteframe-z2" md-component-id="left" md-is-locked-open="sidebar == true">
      <md-content layout-padding layout="column">
        <img ng-src="img/icons/logo.png" alt="Ptolemy - The Network Cartographer" style="padding-left:40px" layout-align="center center">
        <!-- <img ng-src="img/icons/glyphicons_collapse.png" alt="Hide" style="padding-left:40px" layout-align="center center"> -->
      </md-content>
      <md-button class="md-primary" layout-align="bottom right" ng-click="hideSideNav()" ng-show="sidebar == true"> Hide </md-button>
    </md-sidenav>
    <md-button class="md-primary" layout-align="bottom right" ng-click="hideSideNav()" ng-show="sidebar == false"> Hide </md-button>
    <md-content flex layout-padding>

    	<md-toolbar class="md-theme-indigo">
        	<h1 class="md-toolbar-tools">Home</h1>
      	</md-toolbar>

      <!-- Page 1 : Choose between Existing Template or download a Sample Template button -->

      <div layout="column" layout-fill layout-align="top center" ng-show="pageOneVisible">
        <md-card>
              <md-card-content>
                <h2 class="md-title">Configuration</h2>
                <md-switch class="md-primary" md-no-ink ng-model="templateSwitch" ng-change="onTemplateSwitchChange(templateSwitch)">
                Develop using Existing Template</md-switch>
                <span>
                <label for="file-input" style="margin-left:20px">Browse Template</label>  
                <input id="file-input" style="margin-left:10px" type="file" accept=".ptpl" ng-disabled="isTemplateDisabled" on-read-file="loadTemplate($fileContent)">

                <md-button class="md-raised md-primary" ng-click="downloadSampleTemplate()">Download Sample Template</md-button>
                <a href="downloadUrl" id="fileDownloadLink" ng-hide="true"></a>
                </span>
                <div ng-show="templateUploaded == true">
                  <h3>Template</h3>
                    <md-checkbox md-no-ink ng-init="showPasswords == false" class="md-primary" ng-model="showPasswords" aria-label="Show Password" ng-true-value="true" ng-false-value="false"> Show Passwords</md-checkbox>
                    <pre ng-show="showPasswords == true">{{ template }}</pre>
                    <pre ng-show="showPasswords == false">{{ passwordEncodedTemplate }}</pre>
                  <!-- </span> -->

                </div>


                </md-card-content>
          </md-card>
          <section layout="row" layout-sm="column" layout-align="center center">
              <md-button class="md-raised md-primary" ng-click="PageTwo()"> Build New Configuration </md-button>
              <md-button class="md-raised md-primary" ng-click="generateGraphFromTemplate(template, $event)"> Generate Graph 
              <md-tooltip> Choose an existing template to generate graph directly or build a new configuration.
              </md-tooltip>
              </md-button>
          </section> 
          <!-- <a id="fileDownloadLink" ng-hide="true" ng-href="downloadUrl" /> -->
      </div>

      <!-- End of Page 1 -->

      <!-- Page 2 - Configuration : Choose Global Credentials -->
      <div layout="column" layout-fill layout-align="top center"  ng-show="pageTwoVisible">
       <md-card>
              <md-card-content>
                <h2 class="md-title">Configuration</h2>
                <md-checkbox md-no-ink class="md-primary" ng-model="global_credentials" aria-label="Use Global User Credentials">
                  Use Global User Credentials
                </md-checkbox>


                <div ng-show="global_credentials == true">

                <!-- Username and Password If User Credentials is chosen -->
                <md-content layout-padding layout="row" layout-sm="column">
                <!-- ng-show="userCredentials" -->
                    <label style="margin-top:10px">Username</label>
                    <input id="username" style="height:30px;margin-top:5px;margin-left:5px" ng-model="global_user.username">
                    <label style="margin-top:10px;margin-left:10px">Password</label>
                    <input id="password" style="height:30px;margin-top:5px;margin-left:5px" ng-model="global_user.password" type="{{passwordField}}">
                    <md-checkbox md-no-ink class="md-primary" ng-model="passwordField" aria-label="Show Password" id="show_password" ng-true-value="'text'" ng-false-value="'password'"> Show Password</md-checkbox>
                </md-content>

                </div>


                 <!-- Settings for Log Generation -->
                <md-content layout-padding layout="row" layout-sm="column" > 

                    <div layout="row">
                      <div flex="50" flex-md="100" layout="column">
                        <fieldset class="standard" flex>
                          <legend>Output Formats</legend>
                          <div layout="row" layout-wrap>
                           <div flex="50" ng-repeat="item in output_formats">
                             <md-checkbox md-no-ink class="md-primary" flex="50" ng-checked="format_exists(item, selected_output_formats)" ng-click="toggle_output_formats(item, selected_output_formats)" aria-label="item">
                                {{ item }}
                            </md-checkbox>
                           </div>
                          </div>
                        </fieldset>
                      </div>

                      <div flex="50" flex-md="100" layout="column">
                        <fieldset class="standard" flex>
                          <legend>Logs</legend>
                          <div layout="row" layout-wrap>
                            <md-radio-group ng-model="log_config" class="md-primary">
                              <md-radio-button value="global_log" class="md-primary">Generate Global Logs</md-radio-button>
                              <md-radio-button value="device"> Generate Logs Per Device </md-radio-button>
                            </md-radio-group>
                          </div>
                        </fieldset>
                      </div>
                    </div>

                </md-content>
      
              </md-card-content>
        </md-card>

        <section layout="row" layout-sm="column" layout-align="center center">
            <md-button class="md-raised md-primary" ng-click="PageOne()" > Back </md-button>
            <md-button class="md-raised md-primary" ng-click="PageThree($event)" > Next </md-button>
           <div class="label" style="visibility: hidden">Raised</div>
        </section> 
      </div>
      <!-- End of Page 2 -->

      <!-- Page 3 - Configuration : Upload CSV and Connection Table -->
      <div layout="column" layout-fill layout-align="top center" ng-show="pageThreeVisible">
       <md-card>
              <md-card-content>
                <h2 class="md-title">Configuration</h2>

                    <!-- Browse CSV File -->
                    <md-content layout-padding layout="row" layout-sm="column" > 
                    <!-- ng-show="sshCredentials" -->
                        <label style="margin-bottom:20px">Connection Details</label>
                        <input type="file" id="connection_details" accept=".csv" style="margin-bottom:20px;margin-left:10px" on-read-file="loadConnectionDetails($fileContent)">
                    </md-content>


              		  <form editable-form name="tableform" onaftersave="saveTable()" oncancel="cancel()">


            			    <!-- table -->
            			    <table class="table table-bordered table-hover table-condensed">
            			      <tr style="font-weight: bold">
            			        <td style="width:40%">Hostname</td>
            			        <td style="width:25%">Username</td>
            			        <td style="width:25%">Password</td>
                          <td style="width:10%">Port</td>
            			        <td style="width:20%"><span ng-show="tableform.$visible">Action</span></td>
            			      </tr>
            			      <tr ng-repeat="device in connectionDetails | filter : filterConnections">
            			        <td>
            			          <!-- editable username (text with validation) -->
            			          <span editable-text="device.hostname" e-form="tableform" ng-show="editableTable == false" onbeforesave="checkHostName($data)">
            			            {{ device.hostname }}
            			          </span>
            			        </td>
            			        <td>
            			          <!-- editable status (select-local) -->
            			          <span editable-text="device.username" e-form="tableform" ng-show="editableTable == false" onbeforesave="checkUserName($data)">
            			            {{ device.username }}
            			          </span>
            			        </td>
            			        <td>
            			          <!-- editable group (select-remote) -->
            			          <span editable-password="<PASSWORD>" e-form="tableform" ng-show="editableTable == false" onbeforesave="checkPassword($data)">
            			            <input type="password" name="lname" disabled value="{{ device.password }}">
            			          </span>
            			        </td>
                          <td>
                            <!-- editable group (select-remote) -->
                            <span editable-text="device.port" e-form="tableform" ng-show="editableTable == false">
                              {{ device.port }}
                            </span>
                          </td>
            			        <td><md-button class="md-raised md-warn" ng-show="tableform.$visible" ng-click="deleteConnectionDetail(device.hostname)">Delete</md-button></td>
            			      </tr>
            			    </table>

            			    <!-- buttons -->
            			    <div class="btn-edit">
            			      <md-button  type="button" class="md-raised md-primary" ng-show="!tableform.$visible" ng-click="tableform.$show()">
            			        edit
            			      </md-button >
            			    </div>
            			    <div class="btn-form" ng-show="tableform.$visible">
            			      <md-button  type="button" ng-disabled="tableform.$waiting" ng-click="addNewConnectionDetail()" class="md-raised md-primary">add device</md-button >
            			      <md-button  type="submit" ng-disabled="tableform.$waiting" class="md-raised md-primary">confirm</md-button >
            			      <md-button  type="button" ng-disabled="tableform.$waiting" ng-click="tableform.$cancel()" class="md-raised md-primary">cancel</md-button >
            			    </div> 
        			    
        			  </form>

                </md-card-content>
          </md-card>

          <section layout="row" layout-sm="column" layout-align="center center">
              <md-button class="md-raised md-primary" ng-click="PageTwo()" > Back </md-button>
              <md-button class="md-raised md-primary" ng-click="PageFour($event)" > Generate Graph </md-button>
             <div class="label" style="visibility: hidden">Raised</div>
          </section> 

      </div>
      <!-- End of Page 3 -->


      <!-- Page 4 - Content showing Generated graph and other options -->
      <div layout="column" layout-fill layout-align="top center" ng-show="pageFourVisible">
       <md-card>
              <md-card-content>
                <div>
                  <h1 class="md-title">Network Topology</h1>
                  <span>
                  <label>View As</label>
                  <md-select placeholder="Content Type" ng-model="view_format">
                    <md-option ng-repeat="view_format in selected_output_formats" value="{{view_format}}">{{view_format}}</md-option>
                  </md-select>
                  <md-button class="md-raised md-primary" ng-click="" > Download </md-button>
                  <md-button class="md-raised md-primary" ng-click="" > Download All Formats </md-button>
                  <md-button class="md-raised md-primary" ng-click="" > Save Configuration as Template </md-button>
                  </span>

                  <!-- View to Indicate that work is in progress -->
                  <div id="loading_div" ng-show="loading == true">
                      <h4>This might take a while. Please wait...</h4>
                      <div layout="row" layout-sm="column" layout-align="space-around">
                        <md-progress-circular md-mode="indeterminate"></md-progress-circular>
                      </div>
                  </div>
                  <!-- View to Show the results -->
                  <div id='content_view' ng-show="loading == false" style="overflow:auto;height:60%;width:100%;margin-top:20px;margin-bottom:10px">
                  </div>
                </div>
              </md-card-content>
          </md-card>

          <section layout="row" layout-sm="column" layout-align="center center">
              <md-button class="md-raised md-primary" ng-click="PageThree()" > Back </md-button>
              <md-button class="md-raised md-primary" ng-click="PageOne()" > Start Again </md-button>
             <div class="label" style="visibility: hidden">Raised</div>
          </section> 

      </div>
      <!-- End of Page 4 -->


     <div flex></div>

    </md-content>


    <!-- Right Side Navigator -->
    <!-- <md-sidenav class="md-sidenav-right md-whiteframe-z2" md-component-id="right">
      <md-toolbar class="md-theme-light">
        <h1 class="md-toolbar-tools">Sidenav Right</h1>
      </md-toolbar>
      <md-content layout-padding>
        <form>
          <md-input-container>
            <label for="testInput">Test input</label>
            <input type="text" id="testInput"
                   ng-model="data" md-sidenav-focus>
          </md-input-container>
        </form>
        <md-button ng-click="close()" class="md-primary">
          Close Sidenav Right
        </md-button>
      </md-content>
    </md-sidenav> -->
    <!-- End of Right side navigator -->

  </section>
</div>


<script>
var app = angular.module('myApp', ['ngMaterial','xeditable']);
app.controller('AppCtrl', function ($scope, $timeout, $mdSidenav, $mdUtil, $mdDialog, $log, $filter, $http, $q) {

  $scope.isTemplateDisabled = true;
  $scope.global_credentials = false;
  $scope.passwordField = "password";

  $scope.editableTable = false;
  $scope.connectionDetailsUploaded = false;
  $scope.templateUploaded = false;
  $scope.templateEditable = false;
  $scope.showPasswords = false;

  $scope.configuration = [];

  $scope.connectionDetails = [];

	$scope.pageOneVisible = true;
	$scope.pageTwoVisible = false;
	$scope.pageThreeVisible = false;
  $scope.sidebar = true;
  $scope.log_config = "global_log";
  $scope.output_formats = ["DOT","JSON","SVG","PDF","PNG"];
  $scope.selected_output_formats = ["DOT","JSON","SVG","PDF","PNG"];


  $scope.toggle_output_formats = function (item, list) {
        var idx = list.indexOf(item);
        if (idx > -1) list.splice(idx, 1);
        else list.push(item);
  };

  $scope.format_exists = function (item, list) {
        return list.indexOf(item) > -1;
  };

  $scope.hideSideNav = function () {
   $mdSidenav('left').close();
   $scope.sidebar = !$scope.sidebar;
  }

	$scope.PageOne = function () {
		$scope.pageOneVisible = true;
		$scope.pageTwoVisible = false;
		$scope.pageThreeVisible = false;
    $scope.pageFourVisible = false;
    }

	$scope.PageTwo = function () {
		$scope.pageOneVisible = false;
		$scope.pageTwoVisible = true;
		$scope.pageThreeVisible = false;
    $scope.pageFourVisible = false;

    // Clear all the configuration since it will be updated on press of next
    $scope.configuration = [];
    $scope.logs = [];

    var request = $http({
                    method: "POST",
                    url: "/ptolemy",
                    data: $scope.configuration
                });
    // Store the data-dump of the FORM scope.
    request.success(
        function( html ) {
            $scope.cfdump = html;
        }
    );

      
		// $http.post("/asd.svg", {file1:$scope.tracediffFile1, file2:$scope.tracediffFile2})
  //     .success(function (response) {
  //       $scope.svgFile = response;

  //       angular.element( document.querySelector( '#svgg' ) ).append($scope.svgFile);
		// $scope.$apply ();
  //     });
    }

	$scope.PageThree = function (ev) {

    //Update the dictionary with configuration details
    $scope.logs = [];

    if ($scope.log_config == 'device') {
      $scope.logs = "Device"
    } else {
      $scope.logs = "Global"
    };
    // Validate if Credentials are entered if gloval credentials is checked
    if (($scope.global_credentials && !$scope.global_user) || ($scope.global_credentials && (!$scope.global_user.username || !$scope.global_user.password))) {
      $mdDialog.show(
          $mdDialog.alert()
            .parent(angular.element(document.body))
            .title('Incomplete Credentials')
            .content('Please enter Username and password or uncheck Global User Credentials to proceed.')
            .ariaLabel('Template Upload')
            .ok('OK')
            .targetEvent(ev)
        );
    } else{

        $scope.pageOneVisible = false;
        $scope.pageTwoVisible = false;
        $scope.pageThreeVisible = true;
        $scope.pageFourVisible = false;

        if ($scope.global_credentials) {
          $scope.user_credentials = {
            "username" : $scope.global_user.username,
            "password" : <PASSWORD>
          };
          $scope.configuration.push({
            "Global Credentials" : $scope.user_credentials,
            "Output Formats" : $scope.selected_output_formats,
            "Logs" : $scope.logs,
            "Connection Details": ""
          });
        } else {
          $scope.configuration.push({
            "Global Credentials" : 'None',
            "Output Formats" : $scope.selected_output_formats,
            "Logs" : $scope.logs,
            "Connection Details": ''
          });
        };
        
    };
  }



  $scope.downloadSampleTemplate = function () {

    var request = $http({
                    method: "POST",
                    url: "/download-sample-template",
                });
    // Store the data-dump of the FORM scope.
    request.success(
        function( response ) {
            $scope.downloadUrl = response.data.fileName;

            var fileDownloadLink = document.getElementById("fileDownloadLink");
            fileDownloadLink.target = "_blank"; // Opens the file in a new window.
            fileDownloadLink.click();
            //$scope.resp = response;
            /*
            $scope.svgFile = response;
            
            if svg file do ::
            angular.element( document.querySelector( '#svgg' ) ).append($scope.svgFile);
            $scope.$apply ();

            for pdf it will be something else.
        */
        }
    );

    }


   $scope.generateGraphFromTemplate =  function (template, ev) {
      if ($scope.templateUploaded) {
        $scope.configuration = JSON.parse(template);
        // Fetch the Output Formats from the JSON Dictionary
        formats = $scope.configuration["Output Formats"];
        $scope.selected_output_formats = [];
        for (index=0;index < formats.length; index++){
          $scope.selected_output_formats.push(formats[index].toUpperCase());
        }

        $scope.GenerateGraph();
      }
      else {
        $mdDialog.show(
          $mdDialog.alert()
            .parent(angular.element(document.body))
            .title('No template uploaded')
            .content('You will have to choose a template or build a new configuration to proceed.')
            .ariaLabel('Template Upload')
            .ok('OK')
            .targetEvent(ev)
        );
      }
    }


  $scope.checkHostName = function(hostname) {
    if (!hostname) {
      return "Please enter a valid hostname.";
    }
  };

  $scope.checkUserName = function(username) {
    if (!$scope.global_credentials && !username) {
      return "Please enter a valid username.";
    }
  };

  $scope.checkPassword = function(password) {
    if (!$scope.global_credentials && !password) {
      return "Please enter a valid password.";
    }
  };

  $scope.PageFour = function (ev) {
    if($scope.connectionDetailsUploaded || ($scope.connectionDetails && $scope.connectionDetails.length > 0  && $scope.connectionDetails[0]['hostname'])){
      // Push Connection Details to Configuration
      $scope.configuration[0]['Connection Details'] = $scope.connectionDetails;
      // Hack to Send it at a dictionary instead of a list of one element
      $scope.configuration = $scope.configuration[0];
      $scope.GenerateGraph();
    } else {
      $mdDialog.show(
          $mdDialog.alert()
            .parent(angular.element(document.body))
            .title('Device Configuration missing')
            .content('You will have to upload a  file containing device connections or build a connection profile.')
            .ariaLabel('Device Configuration')
            .ok('OK')
            .targetEvent(ev)
        );
    }
  }


  $scope.GenerateGraph = function (){
      $scope.pageOneVisible = false;
      $scope.pageTwoVisible = false;
      $scope.pageThreeVisible = false;
      $scope.pageFourVisible = true;
      $scope.loading = true;

      var request = $http({
                    method: "POST",
                    url: "/pageFour",
                    headers : {
                          'Content-Type' : 'application/json'
                        },
                    data: $scope.configuration
                });
      // Store the data-dump of the FORM scope.
      request.success(
          function( response ) {
              $scope.loading = false;
              // Parse the SVG and change the height 
              // Dirty hack to make the SVG fit the div
              var parser = new DOMParser();
              var svgContent = parser.parseFromString(response,"text/xml");
              svgContent.getElementsByTagName("svg")
              $scope.svgFile = response;
              angular.element( document.querySelector( '#content_view' ) ).append($scope.svgFile);
              $scope.$apply ();
          }
      );
  }

  $scope.onTemplateSwitchChange = function(switchValue) {
    $scope.isTemplateDisabled = !switchValue
  }

  $scope.loadConnectionDetails = function($fileContent){
    //Parse the file content and put it into template details
    $scope.connectionDetails = [];
    $scope.fileArray = $fileContent.split("\n");
    // Ignore Line 1 since it will always contain the Headers
    for (index = 1; index < $scope.fileArray.length; index++) {
      var tempArr = $scope.fileArray[index].split(",")
      //Run another for loop to build the configuration
      if (tempArr[0] && tempArr[1]) {
        $scope.connectionDetails.push({
          hostname: tempArr[0],
          username: tempArr[1],
          password: <PASSWORD>],
          path: tempArr[3],
          port: tempArr[4]
        });
      };
    }
    $scope.connectionDetailsUploaded = true;
  };

  $scope.loadTemplate = function($fileContent){
    //Parse the file content and put it into connection details
    $scope.template = $fileContent;
    $scope.passwordEncodedTemplate = JSON.parse($fileContent);
    $scope.passwordEncodedTemplate["Global Credentials"]["password"] = "***";
    for (var i = 0; i < $scope.passwordEncodedTemplate["Connection Details"].length; i++) {
      $scope.passwordEncodedTemplate["Connection Details"]["password"] = "***";
    };
    $scope.templateString = JSON.stringify($scope.template, null, "\t");
    $scope.passwordEncodedTemplateString = JSON.stringify($scope.passwordEncodedTemplateString, null, "\t");
    $scope.templateUploaded = true;
  };

  // filter users to show
  $scope.filterConnections = function(device) {
    return device.isDeleted !== true;
  };

  // mark device as deleted
  $scope.deleteConnectionDetail = function(hostname) {
    var filtered = $filter('filter')($scope.connectionDetails, {hostname: hostname});
    if (filtered.length) {
      filtered[0].isDeleted = true;
    }
  };

  // add device
  $scope.addNewConnectionDetail = function() {
    $scope.connectionDetails.push({
      hostname: '', 
      username: '', 
      password: '', 
      path: '', 
      port: '',
      isNew: true
    });
  };

  // cancel all changes
  $scope.cancel = function() {
    for (var i = $scope.connectionDetails.length; i--;) {
      var device = $scope.connectionDetails[i];    
      // undelete
      if (device.isDeleted) {
        delete device.isDeleted;
      }
      // remove new 
      if (device.isNew) {
        $scope.connectionDetails.splice(i, 1);
      }      
    };

  };

  // save edits
  $scope.saveTable = function() {
    var results = [];
    for (var i = $scope.connectionDetails.length; i--;) {
      var device = $scope.connectionDetails[i];
      // actually delete user
      if (device.isDeleted) {
        $scope.connectionDetails.splice(i, 1);
      }
      // mark as not new 
      if (device.isNew) {
        device.isNew = false;
      }
  
{'fraction_non_alphanumeric': 0.1528536855095924, 'fraction_numerical': 0.010962768259259853, 'mean_word_length': 1.9815071438811105, 'pattern_counts': {'":': 4, '<': 698, '<?xml version=': 0, '>': 698, 'https://': 12, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 38, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2794453', 'n_tokens_mistral': 18890, 'n_tokens_neox': 17756, 'n_words': 3444}