View Javadoc
1   /*
2    * Copyright (c) Patrick Magauran 2018.
3    *   Licensed under the AGPLv3. All conditions of said license apply.
4    *       This file is part of ABOS.
5    *
6    *       ABOS is free software: you can redistribute it and/or modify
7    *       it under the terms of the GNU Affero General Public License as published by
8    *       the Free Software Foundation, either version 3 of the License, or
9    *       (at your option) any later version.
10   *
11   *       ABOS is distributed in the hope that it will be useful,
12   *       but WITHOUT ANY WARRANTY; without even the implied warranty of
13   *       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   *       GNU Affero General Public License for more details.
15   *
16   *       You should have received a copy of the GNU Affero General Public License
17   *       along with ABOS.  If not, see <http://www.gnu.org/licenses/>.
18   */
19  
20  package Controllers;
21  
22  import Utilities.*;
23  import com.lynden.gmapsfx.GoogleMapView;
24  import com.lynden.gmapsfx.javascript.event.UIEventType;
25  import com.lynden.gmapsfx.javascript.object.*;
26  import javafx.fxml.FXML;
27  import javafx.fxml.FXMLLoader;
28  import javafx.fxml.Initializable;
29  import javafx.scene.control.Button;
30  import javafx.scene.control.Label;
31  import javafx.scene.layout.HBox;
32  import javafx.scene.layout.Pane;
33  import javafx.scene.layout.VBox;
34  import netscape.javascript.JSObject;
35  
36  import java.io.IOException;
37  import java.net.URL;
38  import java.sql.Connection;
39  import java.sql.PreparedStatement;
40  import java.sql.ResultSet;
41  import java.sql.SQLException;
42  import java.util.ArrayList;
43  import java.util.HashMap;
44  import java.util.List;
45  import java.util.ResourceBundle;
46  
47  @SuppressWarnings("WeakerAccess")
48  
49  public class MapController implements Initializable {
50  
51      //  public HBox custOrders;
52      // public Label custAddress;
53      //public Label custPhone;
54      //public Label custName;
55      @FXML
56      private VBox infoPanel;
57      @FXML
58      private Button button;
59  
60      @FXML
61      private GoogleMapView googleMapView;
62  
63      private MainController mainCont;
64      private HashMap<LatLongComparable, ArrayList<Customer>> customersToClick = new HashMap<>();
65  
66      @Override
67      public void initialize(URL url, ResourceBundle rb) {
68  
69      }
70  
71      protected void configureMap() {
72          try {
73              MapOptions mapOptions = new MapOptions();
74  
75              mapOptions.center(new LatLong(47.6097, -122.3331))
76                      .mapType(MapTypeIdEnum.ROADMAP).zoom(9);
77  
78  
79              //initMap();
80              final double[] totCoords = {0, 0, 0};
81              double totLat = 0;
82              final double[] totLon = {0};
83              HashMap<Marker, LatLongComparable> markers = new HashMap<>();
84  /*        List<String> Addr = getAllCustomersInfo("ADDRESS");
85          List<String> Town = getAllCustomersInfo("TOWN");
86          List<String> State = getAllCustomersInfo("STATE");
87  
88          List<String> latL = getAllCustomersInfo("Lat");
89          List<String> lonL = getAllCustomersInfo("Lon");
90          List<String> Ord = getAllCustomersInfo("Ordered");
91          List<String> NI = getAllCustomersInfo("NI");
92          List<String> NH = getAllCustomersInfo("NH");*/
93              //cPoints = new Object[Addr.size()];
94              Iterable<String> years = DbInt.getUserYears();
95              // List<LatLong> customers = new ArrayList<LatLong>();
96              years.forEach(year -> {
97                  List<String> ret = new ArrayList<>();
98                  Year yearObj = new Year(year);
99                  yearObj.getCustomers().forEach(customer -> {
100                     LatLongComparable custLatLong = new LatLongComparable(customer.getLat(), customer.getLon());
101                     if (!customersToClick.containsKey(custLatLong)) {
102                         double lat = customer.getLat();
103                         double lon = customer.getLon();
104                         totCoords[0] += lat;
105                         totCoords[1] += lon;
106                         MarkerOptions opts = new MarkerOptions();
107                         String address = customer.getAddr();
108                         String cName = customer.getName();
109 
110                         opts.title(cName + " " + address + " " + customer.getCustAddressFrmName()[0] + ", " + customer.getCustAddressFrmName()[1]);
111                         opts.position(new LatLong(lat, lon));
112                         Marker m = new Marker(opts);
113 
114                         // cPoints[i] = new Utilities.cPoint(lat, lon, Addr.get(i), Town.get(i), State.get(i));
115                         //Determine color of dot
116                         //Green = orderd
117                         //Cyan = Not Interested
118                         //Magenta = not home
119             /*if (Ord.get(Ord.size() - 1).equals("True")) {
120                 m.setBackColor(Color.GREEN);
121             }
122             if (NI.get(NI.size() - 1).equals("True")) {
123                 m.setBackColor(Color.CYAN);
124             }
125             if (NH.get(NH.size() - 1).equals("True")) {
126                 m.setBackColor(Color.MAGENTA);
127             }*/
128                         //String id = getCustInfo("Set", "CUSTOMERID", Addr.get(i)).get(0);
129                         markers.put(m, custLatLong);
130                         totCoords[2]++;
131                         ArrayList<Customer> customs = new ArrayList();
132                         customs.add(customer);
133                         customersToClick.put(custLatLong, customs);
134 
135                     } else {
136                         customersToClick.get(custLatLong).add(customer);
137                     }
138                 });
139 
140             });
141             GoogleMap map = googleMapView.createMap(mapOptions, false);
142 
143 
144             markers.forEach((m, latLon) -> {
145                 map.addMarker(m);
146                 map.addUIEventHandler(m, UIEventType.click, (JSObject obj) -> markerClicked(latLon));
147             });
148 
149             map.setCenter(new LatLong(totCoords[0] / totCoords[2], totCoords[1] / totCoords[2]));
150 
151 
152         } catch (Exception e) {
153             LogToFile.log(e, Severity.WARNING, "Error loading map");
154         }
155 
156 
157     }
158 
159     public void initMap(MainController mainController) {
160         mainCont = mainController;
161         googleMapView.addMapInializedListener(() -> configureMap());
162 
163 
164         //new Controllers.MapController(map(), this);
165 
166 
167     }
168 
169     private void markerClicked(LatLongComparable latLong) {
170 
171         //System.out.println(mapMarker + " is clicked");
172         //System.out.println(cP.getAddress());
173         //String address = marker.getTitle();
174 
175         //custAddress.setText(address);
176         //Utilities.Customer cust = new Utilities.Customer()
177 
178         infoPanel.getChildren().clear();
179         // m.OrderStat.setText("Has Ordered");
180                                         /*Get info about customer that has clicked
181                                         Display name Phone  Utilities.Order status
182                                         Creates a button for each ordered year to view more information
183                                         */
184 
185         String Name;
186 
187         List<Customer> customers = customersToClick.get(latLong);
188         HashMap<String, HBox> custNames = new HashMap<>();
189         customers.forEach(customer -> {
190             if (custNames.containsKey(customer.getName())) {
191                 String PhoneD = customer.getPhone();
192 
193 /*                                                if (m.infoPanel.getComponentCount() > 8) {
194                                                     m.infoPanel.remove(m.infoPanel.getComponentCount() - 1);
195 
196                                                 }*/
197                 Button b = new Button(customer.getYear());
198                 b.setOnAction(e1 -> {
199                     Pane newPane = null;
200                     FXMLLoader loader;
201                     String tabTitle;
202                     loader = new FXMLLoader(getClass().getResource("/UI/Customer.fxml"));
203                     try {
204                         newPane = loader.load();
205                     } catch (IOException e) {
206                         LogToFile.log(e, Severity.SEVERE, "Error loading window. Please retry then reinstall application. If error persists, contact the developers.");
207                     }
208                     CustomerController customerCont = loader.getController();
209 
210                     customerCont.initCustomer(customer, mainCont);
211                     tabTitle = ("Customer View - " + customer.getName() + " - " + customer.getYear());
212                     mainCont.addTab(newPane, tabTitle);
213                 });
214                 custNames.get(customer.getName()).getChildren().add(b);
215             } else {
216                 HBox custOrders = new HBox();
217 
218                 Label addrHeader = new Label("Customer address");
219                 Label nameHeader = new Label("Customer Name");
220                 Label phoneHeader = new Label("Customer Phone");
221                 Label orderHeader = new Label("Customer Orders");
222                 addrHeader.getStyleClass().add("Info-Header");
223                 nameHeader.getStyleClass().add("Info-Header");
224                 phoneHeader.getStyleClass().add("Info-Header");
225                 orderHeader.getStyleClass().add("Info-Header");
226 
227                 Label custAddress = new Label(customer.getAddr());
228                 Label custPhone = new Label(customer.getPhone());
229                 Label custName = new Label(customer.getName());
230                 String PhoneD = customer.getPhone();
231                 custNames.put(customer.getName(), custOrders);
232 /*                                                if (m.infoPanel.getComponentCount() > 8) {
233                                                     m.infoPanel.remove(m.infoPanel.getComponentCount() - 1);
234 
235                                                 }*/
236                 Button b = new Button(customer.getYear());
237                 b.setOnAction(e1 -> {
238                     Pane newPane = null;
239                     FXMLLoader loader;
240                     String tabTitle;
241                     loader = new FXMLLoader(getClass().getResource("/UI/Customer.fxml"));
242                     try {
243                         newPane = loader.load();
244                     } catch (IOException e) {
245                         LogToFile.log(e, Severity.SEVERE, "Error loading window. Please retry then reinstall application. If error persists, contact the developers.");
246                     }
247                     CustomerController customerCont = loader.getController();
248 
249                     customerCont.initCustomer(customer, mainCont);
250                     tabTitle = ("Customer View - " + customer.getName() + " - " + customer.getYear());
251                     mainCont.addTab(newPane, tabTitle);
252                 });
253                 custOrders.getChildren().add(b);
254                 VBox info = new VBox(nameHeader, custName, phoneHeader, custPhone, addrHeader, custAddress, orderHeader, custOrders);
255                 info.getStyleClass().add("Map-Info-Box");
256                 info.getStyleClass().add("informationPane");
257 
258                 infoPanel.getChildren().add(info);
259             }
260 
261 
262         });
263 
264 
265 
266                    /* if (NI.get(NI.size() - 1).equals("True")) {
267                         m.OrderStat.setText("Not interested");
268                     }
269                     if (NH.get(NH.size() - 1).equals("True")) {
270                         m.OrderStat.setText("Not home");
271                     }*/
272 
273 
274     }
275 
276 // --Commented out by Inspection START (1/2/2016 12:01 PM):
277 //    private static Coordinate c(double lat, double lon) {
278 //        return new Coordinate(lat, lon);
279 //    }
280 // --Commented out by Inspection STOP (1/2/2016 12:01 PM)
281 
282 // --Commented out by Inspection START (2/1/16 5:28 PM):
283 //    public void main(String... args) {
284 //        Map window = new Map();
285 //        window.setVisible(true);
286 //        map().setDisplayToFitMapElements(true, false, false);
287 //
288 //
289 //    }
290 // --Commented out by Inspection STOP (2/1/16 5:28 PM)
291 
292 // --Commented out by Inspection START (1/2/2016 12:01 PM):
293 //    /**
294 //     * Create the application.
295 //     */
296 ///*	public Map() {
297 //        initialize();
298 //		try {
299 ////			Object[][] coords = GetCoords("1833 Rowland Rd Abington, PA");
300 ////			System.out.println(coords[0][0]);
301 ////			System.out.println(coords[0][1]);
302 //		}
303 //			catch(java.lang.Exception e) {
304 //					System.out.println(e.toString());
305 //			}
306 //		}*/
307 //    public Object[] getCPoints() {
308 //        return cPoints;
309 //    }
310 // --Commented out by Inspection STOP (1/2/2016 12:01 PM)
311 
312     /**
313      * Getsx the requested info on customers
314      *
315      * @param info Info to retrieve
316      * @return The info requested in ArrayList form
317      */
318     private List<String> getAllCustomersInfo(String info) {
319         List<String> ret = new ArrayList<>();
320 
321         try (Connection con = DbInt.getConnection("Set");
322              PreparedStatement prep = con.prepareStatement("SELECT * FROM Customers", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
323              ResultSet rs = prep.executeQuery()) {
324             while (rs.next()) {
325 
326                 ret.add(rs.getString(info));
327 
328             }
329             ////Utilities.DbInt.pCon.close()
330 
331         } catch (SQLException e) {
332             LogToFile.log(e, Severity.SEVERE, CommonErrors.returnSqlMessage(e));
333         }
334         return ret;
335     }
336 
337     private List<String> getCustInfo(String Db, String info, String Address) {
338         List<String> ret = new ArrayList<>();
339 
340 
341         try (Connection con = DbInt.getConnection(Db);
342              PreparedStatement prep = con.prepareStatement("SELECT * FROM Customers WHERE ADDRESS=?", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) {
343             prep.setString(1, Address);
344             try (ResultSet rs = prep.executeQuery()) {
345 
346                 while (rs.next()) {
347 
348                     ret.add(rs.getString(info));
349 
350                 }
351             }
352             ////Utilities.DbInt.pCon.close()
353 
354         } catch (SQLException e) {
355             LogToFile.log(e, Severity.SEVERE, CommonErrors.returnSqlMessage(e));
356         }
357         return ret;
358     }
359 
360     class LatLongComparable extends LatLong {
361 
362         public LatLongComparable(double latitude, double longitude) {
363             super(latitude, longitude);
364         }
365 
366         @Override
367         public int hashCode() {
368             return Double.hashCode(getLatitude()) + Double.hashCode(getLongitude());
369         }
370 
371         @Override
372         public boolean equals(Object o) {
373             if (!(o instanceof LatLongComparable)) { return false; }
374             if (o == this) { return true; }
375             LatLongComparable compare = (LatLongComparable) o;
376             return (this.getLatitude() == compare.getLatitude() && this.getLongitude() == compare.getLongitude());
377         }
378     }
379 }