classdef gfx < handle
  properties
    clients %matrix of (lat, long) coordinates of servers
    servers
    torServers

    map %underlying map coordinates
  end

  methods
    %Construct a new Graphics object, given the initial, (lat,long) positions
    %of the underlying map, clients, servers, and tor servers.
    %
    function obj = gfx(map, clients, servers, torServers)
      obj.clients = clients;
      obj.servers = servers;
      obj.torServers = torServers;

      obj.map = map;
    end

    %Given a cell array of the packets in the world, update their graphical
    %position on the map.
    %
    function update(obj, packets);
      %plot the world map and coastlines
      worldmap world;
      plotm(obj.map);

      %plot server locations
      plotm(obj.torServers, 'm.');
      plotm(obj.servers, 'k.');
      plotm(obj.clients, 'r.');

      %TODO: take a flag for plotting different colors clients+packets

      %plot packets
      for i = 1:size(packets, 2);
        plotm(packets{i}.currentPosition, '*', 'color', packets{i}.color);
      end

    end

  end

  methods(Static)
    %Generate a random point on the board in the underlying representation
    %The generated point will be within the polygon represented by a list of x
    %and y points
    %
    %This implementation stochastically halts: generate random points until one
    %lies within the polygon
    %
    %This is a static method because otherwise a cyclic data dependency is
    %created:
    %GFX needs the list of clients on the board, but otherwise to generate the
    %client positions, GFX would need to be fully constructed. This is avoided
    %by passing in the same `map' parameters as for the constructor.
    %
    function p = randomPoint(polyX, polyY);
      p = [180 * (rand() - .5), 360 * (rand() - .5)];

      %iterate until p in inside `map'
      while ~inpolygon(p(1), p(2), polyX, polyY);
        p = [180 * (rand() - .5), 360 * (rand() - .5)];
      end
    end
  end
end
