499a665e9bcc78b7ceb8dbb935729419a2c61cd8
[DHBWCampusApp.git] / app / src / main / java / de / dhbwloe / campusapp / CampusApp.java
1 /* CampusApp.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;
17
18 import android.content.Context;
19 import android.content.Intent;
20 import android.content.res.TypedArray;
21 import android.nfc.NfcAdapter;
22 import android.os.Bundle;
23 import android.support.design.widget.FloatingActionButton;
24 import android.support.design.widget.Snackbar;
25 import android.support.v4.app.FragmentActivity;
26 import android.util.Log;
27 import android.view.KeyEvent;
28 import android.view.View;
29 import android.support.design.widget.NavigationView;
30 import android.support.v4.view.GravityCompat;
31 import android.support.v4.widget.DrawerLayout;
32 import android.support.v7.app.ActionBarDrawerToggle;
33 import android.support.v7.app.AppCompatActivity;
34 import android.support.v7.widget.Toolbar;
35 import android.view.Menu;
36 import android.view.MenuItem;
37 import android.view.inputmethod.EditorInfo;
38 import android.view.inputmethod.InputMethodManager;
39 import android.widget.EditText;
40 import android.widget.ImageView;
41 import android.widget.LinearLayout;
42 import android.widget.TextView;
43
44 import java.util.Date;
45
46 import de.dhbwloe.campusapp.nfcreader.NfcCardListener;
47
48 public class CampusApp extends FragmentActivity {
49     private boolean bSearchActive = false;
50     private CampusAppContext AppContext = null;
51
52     /*
53     * Dev Info:
54     *
55     * Die App besteht aus einer einzigen Activity, auf welcher dynamisch Fragmente platziert werden.
56     * Das Menü, sowie die Headerleiste befinden sich auf der Activity, sind dementsprechend immer verfügbar.
57     *
58     * Zur laufzeit der App wird eine einzige Instanz der Klasse CampusAppContext angelegt.
59     * Dieser Kontext dient als einstiegspunkt für sämmtliche global verfügbaren verwaltungs tools.
60     * Dazu gehören:
61     *   AppContext.getNavigationManager()    NavigationManager   Verwaltet die angezeigten Fragmente und deren Navigation
62     *                                                            .navigatePage("Dashboard")  to navigate to the Dashboard
63     *   ... to be continued ...
64      */
65
66     @Override
67     protected void onCreate(Bundle savedInstanceState) {
68         Log.i("CampusApp", "Event: onCreate");
69         super.onCreate(savedInstanceState);
70         setContentView(R.layout.activity_campus_app);
71
72         // Erstelle neuen AppContext, wenn keiner existiert
73         AppContext = CampusAppContext.getInstance();
74         if(AppContext == null)
75             AppContext = new CampusAppContext(this, R.id.fragment_container, R.id.nav_view);
76         else
77             AppContext.setMainActivity(this);
78
79         // Wenn die App aus dem Ruhezustand (oder auch Orientation change) reaktiviert wird soll nicht zuerst der Splashscreen angezeigt werden.
80         boolean instantRestore = false;
81         if(savedInstanceState != null) {
82             long lastrun = savedInstanceState.getLong("lastrun");
83             lastrun = ((new Date()).getTime()/1000) - lastrun;
84             Log.i("CampusApp", "Restored from Idle state! Idled: "+lastrun+" secs");
85             if(lastrun < 30) {
86                 instantRestore = true;
87
88                 // restore previous Title
89                 AppContext.setTitle(savedInstanceState.getString("activetitle"));
90             }
91
92
93             Bundle contextVars = savedInstanceState.getBundle("savedContextVariables");
94             if(contextVars != null) {
95                 Bundle contextVariables = AppContext.getContextVariables();
96                 contextVariables.putAll(contextVars);
97             }
98         }
99
100         prepareMainUi();
101         if(instantRestore) // orientation change
102             loadMainUi();
103         else
104             // don't add navigation to SlashScreen, or even from SplashScreen to Dashboard to the history log!
105             // it would be very strange to return to the SplashScreen or an "empty" page on return ;)
106             AppContext.getNavigationManager().navigatePage("SplashScreen", null, false);
107
108     }
109
110     @Override
111     public void onSaveInstanceState(Bundle savedInstanceState) {
112         Log.i("CampusApp", "Event: onSaveInstanceState");
113
114         // Save instance state during "restarts" due to orientation changes.
115         // We don't want to see the splash screen everytime the orientation changes ;)
116         savedInstanceState.putLong("lastrun", (new Date()).getTime() / 1000);
117         savedInstanceState.putString("activepage", AppContext.getNavigationManager().getCurrentPageName());
118         TextView titleView = (TextView) findViewById(R.id.title);
119         savedInstanceState.putString("activetitle", titleView.getText().toString());
120
121         Bundle contextVariables = AppContext.getContextVariables();
122         savedInstanceState.putBundle("savedContextVariables", contextVariables);
123
124         // Always call the superclass so it can save the view hierarchy state
125         super.onSaveInstanceState(savedInstanceState);
126     }
127
128     public void prepareMainUi() {
129         ImageView btnOpenSearch = (ImageView) findViewById(R.id.search_button);
130         btnOpenSearch.setVisibility(View.GONE);
131     }
132
133     public void loadMainUi() {
134         ImageView btnOpenSearch = (ImageView) findViewById(R.id.search_button);
135
136         btnOpenSearch.setVisibility(View.VISIBLE);
137         setupActionBar();
138         setupSearchTriggers();
139
140         AppContext.getNfcCardListener().startNfcListener();
141     }
142
143     private void setupActionBar() {
144         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
145         DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
146         ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
147         drawer.setDrawerListener(toggle);
148         toggle.syncState();
149
150         NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
151         navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
152             @SuppressWarnings("StatementWithEmptyBody")
153             @Override
154             public boolean onNavigationItemSelected(MenuItem item) {
155                 // Handle navigation view item clicks here.
156                 int id = item.getItemId();
157
158                 for(CampusAppContext.NavigationItem navitem : AppContext.NAVIGATION_TARGETS) {
159                     if(navitem.navItemId == id) {
160                         AppContext.getNavigationManager().navigatePage(navitem.navTarget);
161                         break;
162                     }
163                 }
164
165                 DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
166                 drawer.closeDrawer(GravityCompat.START);
167                 return true;
168             }
169         });
170     }
171
172     private void setupSearchTriggers() {
173         ImageView btnOpenSearch = (ImageView) findViewById(R.id.search_button);
174         ImageView btnCloseSearch = (ImageView) findViewById(R.id.search_clear);
175         EditText edtSearchInput = (EditText) findViewById(R.id.search_input);
176         TextView txtTitle = (TextView) findViewById(R.id.title);
177
178         // EventListener für Suchfunktion
179         btnOpenSearch.setOnClickListener(new View.OnClickListener() {
180             @Override
181             public void onClick(View view) {
182                 triggerSearchPanel(true);
183             }
184         });
185         edtSearchInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
186             @Override
187             public void onFocusChange(View v, boolean hasFocus) {
188                 EditText edtSearchInput = (EditText) v;
189                 if (!hasFocus && edtSearchInput.getText().length() == 0) {
190                     triggerSearchPanel(false);
191                 }
192             }
193         });
194         edtSearchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
195             @Override
196             public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
197                 if (actionId == EditorInfo.IME_ACTION_SEARCH) {
198                     EditText edtSearchInput = (EditText) v;
199                     triggerSearchAction(edtSearchInput.getText().toString());
200                     triggerSearchPanel(false);
201                     return true;
202                 }
203                 return false;
204             }
205         });
206         btnCloseSearch.setOnClickListener(new View.OnClickListener() {
207             @Override
208             public void onClick(View view) {
209                 EditText edtSearchInput = (EditText) findViewById(R.id.search_input);
210                 edtSearchInput.setText("");
211                 triggerSearchPanel(false);
212             }
213         });
214         txtTitle.setOnClickListener(new View.OnClickListener() {
215             @Override
216             public void onClick(View view) {
217                 triggerSearchPanel(true);
218             }
219         });
220
221     }
222
223     private void triggerSearchPanel(boolean show) {
224         if(bSearchActive == show)
225             return;
226         bSearchActive = show;
227         LinearLayout layTitleContainer = (LinearLayout) findViewById(R.id.title_container);
228         LinearLayout laySearchContainer = (LinearLayout) findViewById(R.id.search_container);
229         EditText edtSearchInput = (EditText) findViewById(R.id.search_input);
230
231         InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
232         if(show) {
233             layTitleContainer.setVisibility(View.GONE);
234             laySearchContainer.setVisibility(View.VISIBLE);
235             edtSearchInput.requestFocus();
236
237             imm.showSoftInput(edtSearchInput, InputMethodManager.SHOW_IMPLICIT);
238         } else {
239             layTitleContainer.setVisibility(View.VISIBLE);
240             laySearchContainer.setVisibility(View.GONE);
241
242             View view = this.getCurrentFocus();
243             if (view != null) {
244                 imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
245             }
246         }
247     }
248
249     private void triggerSearchAction(String query) {
250         Bundle bundle = new Bundle();
251         bundle.putString("query", query);
252
253         AppContext.getNavigationManager().navigatePage("AppSearch", bundle);
254     }
255
256     @Override
257     public void onBackPressed() {
258         DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
259         if (drawer.isDrawerOpen(GravityCompat.START)) {
260             drawer.closeDrawer(GravityCompat.START);
261         } else if(!AppContext.getNavigationManager().back()) {
262             super.onBackPressed(); // trigger system action if internal navigation manager returns false for back()
263         }
264     }
265
266     @Override
267     public boolean onCreateOptionsMenu(Menu menu) {
268         // Inflate the menu; this adds items to the action bar if it is present.
269         getMenuInflater().inflate(R.menu.campus_app, menu);
270         return true;
271     }
272
273     @Override
274     public boolean onOptionsItemSelected(MenuItem item) {
275         // Handle action bar item clicks here. The action bar will
276         // automatically handle clicks on the Home/Up button, so long
277         // as you specify a parent activity in AndroidManifest.xml.
278         int id = item.getItemId();
279
280         //noinspection SimplifiableIfStatement
281         if (id == R.id.action_settings) {
282             return true;
283         }
284
285         return super.onOptionsItemSelected(item);
286     }
287
288     /* nfc listener related callbacks */
289     @Override
290     public void onResume() {
291         if(AppContext == null)
292             AppContext = CampusAppContext.getInstance();
293         if(AppContext == null)
294             AppContext = new CampusAppContext(this, R.id.fragment_container, R.id.nav_view);
295         else
296             AppContext.setMainActivity(this);
297
298         super.onResume();
299         Log.i("CampusApp", "onResume event");
300         AppContext.getNfcCardListener().resumeForefrontDispatcher();
301     }
302
303     @Override
304     public void onPause() {
305         super.onPause();
306         Log.i("CampusApp", "Event: onPause");
307         AppContext.getNfcCardListener().pauseForefrontDispatcher();
308     }
309
310     @Override
311     public void onNewIntent(Intent intent) {
312         if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
313             AppContext.getNfcCardListener().handleNfcEvent(intent);
314         }
315     }
316
317 }