package brn.gui.linktable.diagram.custom.edit.parts;

import org.eclipse.draw2d.Connection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.gmf.runtime.notation.Edge;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.swt.graphics.Color;

import brn.gui.graph.model.LinkTableLink;
import brn.gui.linktable.diagram.edit.parts.LinkTableLinkEditPart;

public class LinkTableLinkEditPartEx extends
LinkTableLinkEditPart {

  public LinkTableLinkEditPartEx(View view) {
    super(view);
  }

  @Override
  protected Connection createConnectionFigure() {
    return new LinkFigureEx();
  }

  public class LinkFigureEx extends LinkFigure {

    org.eclipse.draw2d.PolylineDecoration df;

    public LinkFigureEx() {
      super();
      df = new org.eclipse.draw2d.PolylineDecoration();
      setTargetDecoration(df);
      updateFace();
    }

    public void updateFace() {
      LinkTableLink fwdLink = (LinkTableLink)
        ((Edge)LinkTableLinkEditPartEx.this.getModel()).getElement();

      int metric = fwdLink.getMetric();
      int linkQuality = 0;
      if (metric < 0)
        linkQuality = metric + 100; // metric is rssi
      else
        linkQuality = 10000/metric; // metric is pdr or etx

      // Scale metric to 0..100
      linkQuality = Math.max(0, linkQuality);
      linkQuality = Math.min(100, linkQuality);

      int widthSize = (int)(Math.log10(linkQuality+1) * 2 + 1);
      this.setLineWidth(widthSize);
      if (df != null)
        df.setLineWidth(widthSize);

      // calculate link color value
      int blue_value = -1;
      int red_value = -1;
      if (linkQuality >= 50) {
       red_value = (100 - linkQuality)* 2;
       blue_value = 100;
      } else {
       blue_value = linkQuality * 2;
       red_value = 100;
      }
      red_value = (int) (2.55*red_value);
      blue_value = (int) (2.55*blue_value);

      setForegroundColor(new Color(null, red_value, 0, blue_value));
    }

    @Override
    public void validate() {
      super.validate();
      updateFace();
    }

  }

  @Override
  protected void handleNotificationEvent(Notification notification) {
    if (notification.getNotifier() instanceof LinkTableLink) {
      ((LinkFigureEx)getFigure()).updateFace();
    }
    super.handleNotificationEvent(notification);
  }
}
