Added README.txt and GPL Header to Source Files
[DHBWCampusApp.git] / app / src / main / java / de / dhbwloe / campusapp / mensaplan / MensaplanManager.java
1 /* MensaplanManager.java
2  *
3  * This program is free software: you can redistribute it and/or modify
4  * it under the terms of the GNU General Public License as published by
5  * the Free Software Foundation, either version 3 of the License, or
6  * (at your option) any later version.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program. If not, see <http://www.gnu.org/licenses/>.
15  */
16 package de.dhbwloe.campusapp.mensaplan;
17 import android.util.Log;
18
19 import java.io.UnsupportedEncodingException;
20 import java.net.URLEncoder;
21 import java.text.DateFormat;
22 import java.text.NumberFormat;
23 import java.text.ParseException;
24 import java.text.SimpleDateFormat;
25 import java.util.ArrayList;
26 import java.util.Date;
27 import java.util.List;
28 import java.util.Locale;
29 import java.util.regex.Matcher;
30 import java.util.regex.Pattern;
31
32 import de.dhbwloe.campusapp.CampusAppContext;
33 import de.dhbwloe.campusapp.network.XmlEntry;
34 import de.dhbwloe.campusapp.network.XmlRequestHelper;
35 import de.dhbwloe.campusapp.search.SearchIndices;
36
37 /**
38  * Created by pk910 on 22.01.2016.
39  */
40 public class MensaplanManager extends XmlRequestHelper {
41     private CampusAppContext AppContext;
42     private boolean bRequestRunning = false;
43     private ArrayList<MensaplanManagerInterface> aCallbackInterfaces = new ArrayList<MensaplanManagerInterface>();
44
45     public MensaplanManager(CampusAppContext context) {
46         AppContext = context;
47     }
48
49     public void performSynchronisation(MensaplanManagerInterface callback) {
50         aCallbackInterfaces.add(callback);
51         if(bRequestRunning)
52             return;
53
54         bRequestRunning = true;
55         String mensaplanUrl = "http://www.swfr.de/index.php?id=1400&type=98&tx_swfrspeiseplan_pi1[apiKey]=c3841e89a2c8c301b890723ecdb786ad&tx_swfrspeiseplan_pi1[ort]=677";
56         requestXmlFromWeb(mensaplanUrl, "plan", "tagesplan");
57     }
58
59     private long getTimeFromDateString(String timestamp) {
60         // 01.03.2016
61         if(timestamp == null)
62             return 0;
63         DateFormat df = new SimpleDateFormat("dd.MM.yyyy", Locale.ENGLISH);
64         try {
65             Date result =  df.parse(timestamp);
66             return result.getTime()/1000;
67         } catch (ParseException e) {
68             return 0;
69         }
70     }
71
72     private int getPriceFromString(String pricestr) {
73         // 2,90€( pro 100g)?
74         if(pricestr == null)
75             return 0;
76         Pattern r = Pattern.compile("^([0-9,]+)€( pro [0-9]+[a-z]+)?$");
77         Matcher m = r.matcher(pricestr);
78         if (m.find()) {
79             NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
80             try {
81                 Number result = nf.parse(m.group(1));
82                 return (int)(result.doubleValue()*100);
83             } catch (ParseException e) {
84                 return 0;
85             }
86         } else
87             return 0;
88     }
89
90     @Override
91     protected void onXmlReceived(List<XmlEntry> entries) {
92         ArrayList<SearchIndices> newIndices = new ArrayList<SearchIndices>();
93
94         Log.i("MPMSync", "Received Mensaplan XML");
95         for(XmlEntry entry : entries) {
96             Log.i("MPMSync", "Parse Tagesplan: "+entry.getAttribute("datum"));
97             long plandate = getTimeFromDateString(entry.getAttribute("datum"));
98             if(plandate == 0)
99                 continue;
100
101             XmlEntry[] menues = XmlEntry.FindXmlEntriesByName(entry, "menue");
102             for(XmlEntry menue : menues) {
103                 XmlEntry centry;
104                 String menuname = menue.getAttribute("art");
105                 Log.i("MPMSync", "Parse menu "+menuname);
106                 if(menuname == null) continue;
107
108                 String additional = menue.getAttribute("zusatz");
109
110                 centry = XmlEntry.FindXmlEntryByName(menue, "name");
111                 String name = (centry == null ? null : centry.getValue());
112
113                 centry = XmlEntry.FindXmlEntryByName(menue, "nameMitUmbruch");
114                 String nameHtml = (centry == null ? null : centry.getValue());
115
116                 centry = XmlEntry.FindXmlEntryByName(menue, "kennzeichnungen");
117                 String notes = (centry == null ? null : centry.getValue());
118
119                 int priceArray[] = new int[4];
120
121                 centry = XmlEntry.FindXmlEntryByName(menue, "studierende");
122                 priceArray[0] = (centry == null ? 0 : getPriceFromString(centry.getValue()));
123                 centry = XmlEntry.FindXmlEntryByName(menue, "angestellte");
124                 priceArray[1] = (centry == null ? 0 : getPriceFromString(centry.getValue()));
125                 centry = XmlEntry.FindXmlEntryByName(menue, "gaeste");
126                 priceArray[2] = (centry == null ? 0 : getPriceFromString(centry.getValue()));
127                 centry = XmlEntry.FindXmlEntryByName(menue, "schueler");
128                 priceArray[3] = (centry == null ? 0 : getPriceFromString(centry.getValue()));
129
130                 MensaTagesplan tagesplan = new MensaTagesplan(plandate, menuname, 0, name, nameHtml, additional, notes, priceArray[0], priceArray[1], priceArray[2], priceArray[3]);
131                 tagesplan.calculateChkSum();
132
133                 AppContext.getDatabaseManager().updateMensaTagesplan(tagesplan);
134
135                 if(tagesplan.getIsNew(true)) {
136                     SearchIndices indices = new SearchIndices("MensaTagesplan#"+tagesplan.getPlanDate()+"|"+tagesplan.getMenuName(), false);
137                     indices.setUpdateTime(tagesplan.getPlanDate());
138                     try {
139                         indices.setTarget("#Mensa#showdate=" + tagesplan.getPlanDate()+"&showmenu=" + URLEncoder.encode(tagesplan.getMenuName(), "UTF-8"));
140                     } catch (UnsupportedEncodingException e) {
141                         indices.setTarget("#Mensa#showdate=" + tagesplan.getPlanDate());
142                     }
143                     indices.setTitle("Mensaplan " + tagesplan.getFormatedDate());
144                     indices.setDescription(tagesplan.getMenuName() + ": " + tagesplan.getName());
145                     indices.addKeyWord(tagesplan.getName());
146                     indices.addKeyWord(tagesplan.getNotes());
147                     newIndices.add(indices);
148                 }
149             }
150         }
151
152         SearchIndices[] newIndicesArr = new SearchIndices[newIndices.size()];
153         newIndicesArr = newIndices.toArray(newIndicesArr);
154         AppContext.addSearchIndices(newIndicesArr);
155
156         for(MensaplanManagerInterface callback : aCallbackInterfaces) {
157             callback.onMensaplanUpdateDone();
158         }
159         aCallbackInterfaces.clear();
160         bRequestRunning = false;
161     }
162
163     @Override
164     protected void onXmlRequestFail(int statusCode, String errorMessage) {
165         for(MensaplanManagerInterface callback : aCallbackInterfaces) {
166             callback.onMensaplanUpdateFail("error " + statusCode + ": " + errorMessage);
167         }
168         aCallbackInterfaces.clear();
169         bRequestRunning = false;
170     }
171 }