@package   Plugin Monitoring for GLPI
  @author    David Durieux
  @co-author 
  @comment   
  @copyright Copyright (c) 2011-2013 Plugin Monitoring for GLPI team
  @license   AGPL License 3.0 or (at your option) any later version
             http://www.gnu.org/licenses/agpl-3.0-standalone.html
  @link      https://forge.indepnet.net/projects/monitoring/
  @since     2011

  ------------------------------------------------------------------------
*/
include "../../../inc/includes.php";
PluginMonitoringProfile::checkRight("weathermap", "w");
Html::header(__('Monitoring', 'monitoring'), $_SERVER["PHP_SELF"], "plugins", "monitoring", "weathermaplink");
$pmWeathermaplink = new PluginMonitoringWeathermaplink();
if (isset($_POST["add"])) {
    $split = explode("-", $_POST['linksource']);
    $_POST['plugin_monitoring_weathermapnodes_id_1'] = $split[0];
    $_POST['plugin_monitoring_services_id'] = $split[1];
    $pmWeathermaplink->add($_POST);
    Html::back();
} else {
    if (isset($_POST["update"])) {
        $_POST['id'] = $_POST['id_update'];
        unset($_POST['plugin_monitoring_weathermapnodes_id_1']);
        unset($_POST['plugin_monitoring_weathermapnodes_id_2']);
        $_POST['bandwidth_in'] = $_POST['up_bandwidth_in'];
        $_POST['bandwidth_out'] = $_POST['up_bandwidth_out'];
        $pmWeathermaplink->update($_POST);
        Html::back();
    if ($_POST['x'] == '') {
        Html::back();
        exit;
    }
    $pmWeathermapnode->add($_POST);
    Html::back();
} else {
    if (isset($_POST["update"])) {
        if ($_POST['x'] == '') {
            Html::back();
            exit;
        }
        unset($_POST['name']);
        $_POST['name'] = $_POST['nameupdate'];
        unset($_POST['itemtype']);
        $_POST['id'] = $_POST['id_update'];
        $pmWeathermapnode->update($_POST);
        Html::back();
    } else {
        if (isset($_POST["purge"])) {
            $pmWeathermaplink = new PluginMonitoringWeathermaplink();
            $a_links = $pmWeathermaplink->find("`plugin_monitoring_weathermapnodes_id_1`='" . $_POST['id'] . "'\n      OR `plugin_monitoring_weathermapnodes_id_2`='" . $_POST['id'] . "'");
            foreach ($a_links as $data) {
                $pmWeathermaplink->delete($data);
            }
            $pmWeathermapnode->delete($_POST);
            Html::back();
        }
    }
}
Html::footer();
   function drawMap($weathermaps_id, $widthw=100, $config=0) {
      global $DB, $CFG_GLPI;

      $this->getFromDB($weathermaps_id);

      PluginMonitoringSecurity::updateSession();

      if (countElementsInTable('glpi_plugin_monitoring_weathermapnodes', "`plugin_monitoring_weathermaps_id`='".$weathermaps_id."'") == 0) {
         return;
      }

      $rand = mt_rand();
      echo '<svg id="cloud'.$rand.'" width="'.$this->fields['width'].'" '
              . 'height="'.$this->fields['height'].'">
  <defs>
    <marker id="arrowhead'.$rand.'" orient="auto" markerWidth="2" markerHeight="4"
            refX="0.3" refY="0.8">
      <path d="M0,0 V1.6 L0.8,0.8 Z" fill="#d0d0d0" />
    </marker>
    <marker id="arrowheadred'.$rand.'" orient="auto" markerWidth="2" markerHeight="4"
            refX="0.3" refY="0.8">
      <path d="M0,0 V1.6 L0.8,0.8 Z" fill="red" />
    </marker>
    <marker id="arrowheadblack'.$rand.'" orient="auto" markerWidth="2" markerHeight="4"
            refX="0.3" refY="0.8">
      <path d="M0,0 V1.6 L0.8,0.8 Z" fill="black" />
    </marker>
  </defs>
        </svg>';

      echo '<script>
      var width = '.$this->fields['width'].';
      var height = '.$this->fields['height'].';

      var color = d3.scale.category10();

      var force'.$rand.' = d3.layout.force()
          .charge(-180)
          .linkDistance(20)
          .size([width, height]);

      var svg'.$rand.' = d3.select("#cloud'.$rand.'");

      var drag_node = d3.behavior.drag()
        .on("drag", dragmove)';
      if ($config) {
         echo '
        .on("dragend", dragendconfig)';
      }

              echo ';


      function dragmove(d, i) {
        d.px += d3.event.dx;
        d.py += d3.event.dy;
        d.x += d3.event.dx;
        d.y += d3.event.dy;
        tick'.$rand.'(); // this is the key to make it work together with updating both px,py,x,y on d !
     }

     function dragendconfig(d, i) {
        $.ajax({type: "POST",url: "'.$CFG_GLPI['root_doc'].'/plugins/monitoring/ajax/updateWeathermap.php",data: {id: d.id, x: d.x, y: d.y},success: function(msg) {}});
     }
              ';


      $a_data = array();
      $a_mapping = array();
      $i = 0;
      $query = "SELECT * FROM `".getTableForItemType("PluginMonitoringWeathermapnode")."`
         WHERE `plugin_monitoring_weathermaps_id`='".$weathermaps_id."'
         ORDER BY `name`";
      $result = $DB->query($query);
      while ($data=$DB->fetch_array($result)) {
         $name = $data['name'];
         $url = '';
         if ($name == '') {
            $itemtype = $data['itemtype'];
            $item = new $itemtype();
            $item->getFromDB($data['items_id']);
            $name = $item->getName();
            $url = $item->getLinkURL();
         }
         $a_mapping[$data['id']] = $i;
         $i++;
         $a_textx = array(
             'middle' => 0,
             'start'  => '12',
             'end'    => '-12');
         $texty = 0;
         if ($data['position'] == 'middle') {
            $texty = -13;
         }
         $a_data['nodes'][] = array(
             'name'  => $name,
             'id'    => (int)$data['id'],
             'x'     => ($widthw * $data['x']) / 100,
             'y'     => ($widthw * $data['y']) / 100,
             'fixed' => TRUE,
             "group" => 3,
             "url"   => $url,
             "textposition" => $data['position'],
             "textx" => $a_textx[$data['position']],
             "texty" => $texty,
             "nodeusage" => 'grey'
         );
      }
      $nodes_upusage = array();

      $pmWeathermapnode = new PluginMonitoringWeathermapnode();
      $pmWeathermaplink = new PluginMonitoringWeathermaplink();
      $pmService = new PluginMonitoringService();
      $pmComponent = new PluginMonitoringComponent();
      $a_data['links'] = array();
      $query = "SELECT `glpi_plugin_monitoring_weathermaplinks`.*
            FROM `glpi_plugin_monitoring_weathermaplinks`
         LEFT JOIN `glpi_plugin_monitoring_weathermapnodes`
            ON `plugin_monitoring_weathermapnodes_id_1` = `glpi_plugin_monitoring_weathermapnodes`.`id`
         WHERE `plugin_monitoring_weathermaps_id`='".$weathermaps_id."'";
      $result = $DB->query($query);
      while ($data=$DB->fetch_array($result)) {
         $pmWeathermapnode->getFromDB($data['plugin_monitoring_weathermapnodes_id_2']);

         if (!$pmService->getFromDB($data['plugin_monitoring_services_id'])) {
            $pmWeathermapnode = new PluginMonitoringWeathermapnode();
            $pmWeathermapnode->getFromDB($data['plugin_monitoring_weathermapnodes_id_1']);
            $querytt = "SELECT glpi_plugin_monitoring_services.id FROM `glpi_plugin_monitoring_services`
               LEFT JOIN glpi_plugin_monitoring_componentscatalogs_hosts
                  ON plugin_monitoring_componentscatalogs_hosts_id=glpi_plugin_monitoring_componentscatalogs_hosts.id
               WHERE  networkports_id>0
                  AND itemtype='".$pmWeathermapnode->fields['itemtype']."'
                  AND items_id='".$pmWeathermapnode->fields['items_id']."'";
            $resulttt = $DB->query($querytt);
            $s_id = 0;
            if ($DB->numrows($resulttt) == 1) {
               $datatt = $DB->fetch_assoc($resulttt);
               $input = array(
                   'id'                            => $data['id'],
                   'plugin_monitoring_services_id' => $datatt['id']
               );
               $pmWeathermaplink->update($input);
               $pmWeathermaplink->getFromDB($data['id']);
               $data = $pmWeathermaplink->fields;
            }
         }

         $queryevent = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`
            WHERE `plugin_monitoring_services_id`='".$data['plugin_monitoring_services_id']."'
               ORDER BY `date` DESC
               LIMIT 1";
         $resultevent = $DB->query($queryevent);
         $in = '';
         $out = '';
         $service_exist = 0;
         while ($dataevent=$DB->fetch_array($resultevent)) {
            if ($pmService->getFromDB($data['plugin_monitoring_services_id'])) {
               $pmComponent->getFromDB($pmService->fields['plugin_monitoring_components_id']);

               $matches1 = array();
               preg_match("/".$pmComponent->fields['weathermap_regex_in']."/m", $dataevent['perf_data'], $matches1);
               if (isset($matches1[1])) {
                  $in = $matches1[1];
               }
               $matches1 = array();
               preg_match("/".$pmComponent->fields['weathermap_regex_out']."/m", $dataevent['perf_data'], $matches1);
               if (isset($matches1[1])) {
                  $out = $matches1[1];
               }
               $service_exist = 1;
            } else {
               $pmService->getEmpty();
               $pmComponent->getEmpty();
            }
         }
         if ($service_exist) {
            list($downusage, $downcolor) = $this->getWBandwidth($in, $data['bandwidth_in']);
            list($upusage, $upcolor) = $this->getWBandwidth($out, $data['bandwidth_out']);
         } else {
            $upusage = 100;
            $downusage = 100;
            $upcolor = 'black';
            $downcolor = 'black';
         }
         $a_data['links'][] = array(
             'source'    => $a_mapping[$data['plugin_monitoring_weathermapnodes_id_1']],
             'target'    => $a_mapping[$data['plugin_monitoring_weathermapnodes_id_2']],
             'up'        => $upcolor,
             'down'      => $downcolor,
             'upusage'   => $upusage,
             'downusage' => $downusage,
             'info'      => '',
             'value'     => 1,
             'services_id' => $data['plugin_monitoring_services_id'],
             'components_id' => $pmService->fields['plugin_monitoring_components_id'],
             'rrdtool_template' => $pmComponent->fields['graph_template']
         );
         if (!isset($nodes_upusage[$a_mapping[$data['plugin_monitoring_weathermapnodes_id_1']]])) {
            $nodes_upusage[$a_mapping[$data['plugin_monitoring_weathermapnodes_id_1']]] = array();
         }
         if (!isset($nodes_upusage[$a_mapping[$data['plugin_monitoring_weathermapnodes_id_2']]])) {
            $nodes_upusage[$a_mapping[$data['plugin_monitoring_weathermapnodes_id_2']]] = array();
         }
         array_push($nodes_upusage[$a_mapping[$data['plugin_monitoring_weathermapnodes_id_1']]], $upusage);
         array_push($nodes_upusage[$a_mapping[$data['plugin_monitoring_weathermapnodes_id_2']]], $downusage);
      }

      foreach ($nodes_upusage as $nodes_num=>$datausage) {
         $moyusage = array_sum($datausage)/count($datausage);
         list($usage, $color) = $this->getWBandwidth(array_sum($datausage)/count($datausage), 100);
         if ($moyusage == 0) {
            $color = 'grey';
         }
         $a_data['nodes'][$nodes_num]['nodeusage'] = $color;
      }

      echo 'var jsonstr'.$rand.' = \''.json_encode($a_data).'\';';
      echo 'var json'.$rand.' = JSON.parse(jsonstr'.$rand.');
      force'.$rand.'
        .nodes(json'.$rand.'.nodes)
        .links(json'.$rand.'.links)
        .start();

     ';

      $this->d3jsLink('up', 'usage', $rand);
      $this->d3jsLink('up', 'notusage', $rand);
      $this->d3jsLink('down', 'usage', $rand);
      $this->d3jsLink('down', 'notusage', $rand);

      echo '    var nodes'.$rand.' = svg'.$rand.'.selectAll(".node")
        .data(force'.$rand.'.nodes())
      .enter().append("g")
        .attr("class", "node")
        .call(drag_node)
      .append("a")
        .attr("xlink:href", function (d) { return d.url; })
        .attr("target", "_blank");

//      .on("dragend", function(d){$.ajax({url: "toto",success: function(data) {}})});
//d3.select(this).style("fill", "white");}


    nodes'.$rand.'.append("circle")
       .attr("r", 5)
       .attr("class", function(d) { return "circle" + d.nodeusage; });


    nodes'.$rand.'.append("text")
       .attr("text-anchor", function(d) { return d.textposition; })
       .attr("x", function(d) { return d.textx; })
       .attr("y", function(d) { return d.texty; })
       .attr("dy", ".35em")
       .attr("class", "linklabel")
      .text(function(d) { return d.name; });

   var textdown'.$rand.' = svg'.$rand.'.selectAll("line.link")
       .data(force'.$rand.'.links())
    .enter().append("text")
       .attr("dy", ".25em")
       .attr("text-anchor", "middle")
       .style("pointer-events", "none")
       .attr("class", function(d) { return "linklabel" + d.down;})
       .text(function(d) { return d.downusage + "%";})

   var textup'.$rand.' = svg'.$rand.'.selectAll("line.link")
       .data(force'.$rand.'.links())
    .enter().append("text")
       .attr("dy", ".25em")
       .attr("text-anchor", "middle")
       .style("pointer-events", "none")
       .attr("class", function(d) { return "linklabel" + d.up;})
       .text(function(d) { return d.upusage + "%";})

    force'.$rand.'.on("tick", tick'.$rand.');

    function tick'.$rand.'() {
        linksupusage'.$rand.'.attr("x1", function(d) { return d.source.x; })
            .attr("y1", function(d) { return d.source.y; })
            .attr("x2", function(d) { return d.source.x + (((d.target.x - d.source.x) / 200) * ((d.upusage * 97) / 100)); })
            .attr("y2", function(d) { return d.source.y + (((d.target.y - d.source.y) / 200) * ((d.upusage * 97) / 100)); });

        linksupnotusage'.$rand.'.attr("x1", function(d) { return d.source.x + (((d.target.x - d.source.x) / 200) * ((d.upusage * 97) / 100)); })
            .attr("y1", function(d) { return d.source.y + (((d.target.y - d.source.y) / 200) * ((d.upusage * 97) / 100)); })
            .attr("x2", function(d) { return d.source.x + (((d.target.x - d.source.x) / 200) * 97); })
            .attr("y2", function(d) { return d.source.y + (((d.target.y - d.source.y) / 200) * 97); });

        linksdownusage'.$rand.'.attr("x1", function(d) { return d.target.x; })
            .attr("y1", function(d) { return d.target.y; })
            .attr("x2", function(d) { return d.source.x + Math.round(((d.target.x - d.source.x) / 200) * (200 - ((d.downusage * 97) / 100))); })
            .attr("y2", function(d) { return d.source.y + Math.round(((d.target.y - d.source.y) / 200) * (200 - ((d.downusage * 97) / 100))); });

        linksdownnotusage'.$rand.'.attr("x1", function(d) { return d.source.x + Math.round(((d.target.x - d.source.x) / 200) * (200 - ((d.downusage * 97) / 100))); })
            .attr("y1", function(d) { return d.source.y + Math.round(((d.target.y - d.source.y) / 200) * (200 - ((d.downusage * 97) / 100))); })
            .attr("x2", function(d) { return d.source.x + Math.round(((d.target.x - d.source.x) / 200) * 103); })
            .attr("y2", function(d) { return d.source.y + Math.round(((d.target.y - d.source.y) / 200) * 103); });

        nodes'.$rand.'
            .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
';

         echo '
   textdown'.$rand.'.attr("x", function(d) { return d.source.x + (((d.target.x - d.source.x) / 200) * 130); })
      .attr("y", function(d) { return d.source.y + (((d.target.y - d.source.y) / 200) * 130); });


   textup'.$rand.'.attr("x", function(d) { return d.source.x + (((d.target.x - d.source.x) / 200) * 70); })
      .attr("y", function(d) { return d.source.y + (((d.target.y - d.source.y) / 200) * 70); });

     };
';

echo '        </script>';


   }
  You should have received a copy of the GNU Affero General Public License
  along with Monitoring. If not, see <http://www.gnu.org/licenses/>.

  ------------------------------------------------------------------------

  @package   Plugin Monitoring for GLPI
  @author    David Durieux
  @co-author
  @comment
  @copyright Copyright (c) 2011-2014 Plugin Monitoring for GLPI team
  @license   AGPL License 3.0 or (at your option) any later version
             http://www.gnu.org/licenses/agpl-3.0-standalone.html
  @link      https://forge.indepnet.net/projects/monitoring/
  @since     2012

  ------------------------------------------------------------------------
*/
include "../../../inc/includes.php";
header("Content-Type: text/html; charset=UTF-8");
Html::header_nocache();
$pmWeathermaplink = new PluginMonitoringWeathermaplink();
$pmWeathermaplink->getFromDB($_POST['items_id']);
echo "<br/>";
echo __('Max bandwidth input', 'monitoring') . "&nbsp;:&nbsp;";
echo "<input type='text' name='up_bandwidth_in' value='" . $pmWeathermaplink->fields['bandwidth_in'] . "'/>";
echo "<br/>";
echo __('Max bandwidth output', 'monitoring') . "&nbsp;:&nbsp;";
echo "<input type='text' name='up_bandwidth_out' value='" . $pmWeathermaplink->fields['bandwidth_out'] . "'/>";
echo "<br/>";
echo "<input type='submit' name='update' value=\"" . __('Save') . "\" class='submit'>";