commit 2167050f404ee5fb125c91719803ce0061efa665 Author: pl0301 Date: Wed Nov 26 16:22:36 2025 +0100 init diff --git a/.gradle/7.5.1/checksums/checksums.lock b/.gradle/7.5.1/checksums/checksums.lock new file mode 100644 index 0000000..c474eca Binary files /dev/null and b/.gradle/7.5.1/checksums/checksums.lock differ diff --git a/.gradle/7.5.1/checksums/md5-checksums.bin b/.gradle/7.5.1/checksums/md5-checksums.bin new file mode 100644 index 0000000..1a1d071 Binary files /dev/null and b/.gradle/7.5.1/checksums/md5-checksums.bin differ diff --git a/.gradle/7.5.1/checksums/sha1-checksums.bin b/.gradle/7.5.1/checksums/sha1-checksums.bin new file mode 100644 index 0000000..71e6afa Binary files /dev/null and b/.gradle/7.5.1/checksums/sha1-checksums.bin differ diff --git a/.gradle/7.5.1/dependencies-accessors/dependencies-accessors.lock b/.gradle/7.5.1/dependencies-accessors/dependencies-accessors.lock new file mode 100644 index 0000000..60d76ed Binary files /dev/null and b/.gradle/7.5.1/dependencies-accessors/dependencies-accessors.lock differ diff --git a/.gradle/7.5.1/dependencies-accessors/gc.properties b/.gradle/7.5.1/dependencies-accessors/gc.properties new file mode 100644 index 0000000..e69de29 diff --git a/.gradle/7.5.1/executionHistory/executionHistory.bin b/.gradle/7.5.1/executionHistory/executionHistory.bin new file mode 100644 index 0000000..7931c46 Binary files /dev/null and b/.gradle/7.5.1/executionHistory/executionHistory.bin differ diff --git a/.gradle/7.5.1/executionHistory/executionHistory.lock b/.gradle/7.5.1/executionHistory/executionHistory.lock new file mode 100644 index 0000000..24b6521 Binary files /dev/null and b/.gradle/7.5.1/executionHistory/executionHistory.lock differ diff --git a/.gradle/7.5.1/fileChanges/last-build.bin b/.gradle/7.5.1/fileChanges/last-build.bin new file mode 100644 index 0000000..f76dd23 Binary files /dev/null and b/.gradle/7.5.1/fileChanges/last-build.bin differ diff --git a/.gradle/7.5.1/fileHashes/fileHashes.bin b/.gradle/7.5.1/fileHashes/fileHashes.bin new file mode 100644 index 0000000..432c96d Binary files /dev/null and b/.gradle/7.5.1/fileHashes/fileHashes.bin differ diff --git a/.gradle/7.5.1/fileHashes/fileHashes.lock b/.gradle/7.5.1/fileHashes/fileHashes.lock new file mode 100644 index 0000000..8beb9b0 Binary files /dev/null and b/.gradle/7.5.1/fileHashes/fileHashes.lock differ diff --git a/.gradle/7.5.1/fileHashes/resourceHashesCache.bin b/.gradle/7.5.1/fileHashes/resourceHashesCache.bin new file mode 100644 index 0000000..05494f0 Binary files /dev/null and b/.gradle/7.5.1/fileHashes/resourceHashesCache.bin differ diff --git a/.gradle/7.5.1/gc.properties b/.gradle/7.5.1/gc.properties new file mode 100644 index 0000000..e69de29 diff --git a/.gradle/8.7/checksums/checksums.lock b/.gradle/8.7/checksums/checksums.lock new file mode 100644 index 0000000..69dee5a Binary files /dev/null and b/.gradle/8.7/checksums/checksums.lock differ diff --git a/.gradle/8.7/checksums/md5-checksums.bin b/.gradle/8.7/checksums/md5-checksums.bin new file mode 100644 index 0000000..2fc21b0 Binary files /dev/null and b/.gradle/8.7/checksums/md5-checksums.bin differ diff --git a/.gradle/8.7/checksums/sha1-checksums.bin b/.gradle/8.7/checksums/sha1-checksums.bin new file mode 100644 index 0000000..279f22c Binary files /dev/null and b/.gradle/8.7/checksums/sha1-checksums.bin differ diff --git a/.gradle/8.7/dependencies-accessors/gc.properties b/.gradle/8.7/dependencies-accessors/gc.properties new file mode 100644 index 0000000..e69de29 diff --git a/.gradle/8.7/executionHistory/executionHistory.bin b/.gradle/8.7/executionHistory/executionHistory.bin new file mode 100644 index 0000000..0b909a0 Binary files /dev/null and b/.gradle/8.7/executionHistory/executionHistory.bin differ diff --git a/.gradle/8.7/executionHistory/executionHistory.lock b/.gradle/8.7/executionHistory/executionHistory.lock new file mode 100644 index 0000000..6e74a89 Binary files /dev/null and b/.gradle/8.7/executionHistory/executionHistory.lock differ diff --git a/.gradle/8.7/fileChanges/last-build.bin b/.gradle/8.7/fileChanges/last-build.bin new file mode 100644 index 0000000..f76dd23 Binary files /dev/null and b/.gradle/8.7/fileChanges/last-build.bin differ diff --git a/.gradle/8.7/fileHashes/fileHashes.bin b/.gradle/8.7/fileHashes/fileHashes.bin new file mode 100644 index 0000000..4153b3c Binary files /dev/null and b/.gradle/8.7/fileHashes/fileHashes.bin differ diff --git a/.gradle/8.7/fileHashes/fileHashes.lock b/.gradle/8.7/fileHashes/fileHashes.lock new file mode 100644 index 0000000..0d58ef5 Binary files /dev/null and b/.gradle/8.7/fileHashes/fileHashes.lock differ diff --git a/.gradle/8.7/fileHashes/resourceHashesCache.bin b/.gradle/8.7/fileHashes/resourceHashesCache.bin new file mode 100644 index 0000000..c560037 Binary files /dev/null and b/.gradle/8.7/fileHashes/resourceHashesCache.bin differ diff --git a/.gradle/8.7/gc.properties b/.gradle/8.7/gc.properties new file mode 100644 index 0000000..e69de29 diff --git a/.gradle/buildOutputCleanup/buildOutputCleanup.lock b/.gradle/buildOutputCleanup/buildOutputCleanup.lock new file mode 100644 index 0000000..538e89d Binary files /dev/null and b/.gradle/buildOutputCleanup/buildOutputCleanup.lock differ diff --git a/.gradle/buildOutputCleanup/cache.properties b/.gradle/buildOutputCleanup/cache.properties new file mode 100644 index 0000000..5802e11 --- /dev/null +++ b/.gradle/buildOutputCleanup/cache.properties @@ -0,0 +1,2 @@ +#Mon Nov 10 14:27:14 CET 2025 +gradle.version=8.7 diff --git a/.gradle/buildOutputCleanup/outputFiles.bin b/.gradle/buildOutputCleanup/outputFiles.bin new file mode 100644 index 0000000..0a8ad1f Binary files /dev/null and b/.gradle/buildOutputCleanup/outputFiles.bin differ diff --git a/.gradle/config.properties b/.gradle/config.properties new file mode 100644 index 0000000..2553084 --- /dev/null +++ b/.gradle/config.properties @@ -0,0 +1,2 @@ +#Sat Apr 26 00:35:27 CEST 2025 +java.home=/home/darek/.jdks/jbr-17.0.14 diff --git a/.gradle/file-system.probe b/.gradle/file-system.probe new file mode 100644 index 0000000..7acf753 Binary files /dev/null and b/.gradle/file-system.probe differ diff --git a/.gradle/vcs-1/gc.properties b/.gradle/vcs-1/gc.properties new file mode 100644 index 0000000..e69de29 diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/AndroidProjectSystem.xml b/.idea/AndroidProjectSystem.xml new file mode 100644 index 0000000..4a53bee --- /dev/null +++ b/.idea/AndroidProjectSystem.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/caches/deviceStreaming.xml b/.idea/caches/deviceStreaming.xml new file mode 100644 index 0000000..6f03899 --- /dev/null +++ b/.idea/caches/deviceStreaming.xml @@ -0,0 +1,1041 @@ + + + + + + \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..b589d56 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/copilot.data.migration.agent.xml b/.idea/copilot.data.migration.agent.xml new file mode 100644 index 0000000..4ea72a9 --- /dev/null +++ b/.idea/copilot.data.migration.agent.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/copilot.data.migration.ask.xml b/.idea/copilot.data.migration.ask.xml new file mode 100644 index 0000000..7ef04e2 --- /dev/null +++ b/.idea/copilot.data.migration.ask.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/copilot.data.migration.ask2agent.xml b/.idea/copilot.data.migration.ask2agent.xml new file mode 100644 index 0000000..1f2ea11 --- /dev/null +++ b/.idea/copilot.data.migration.ask2agent.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/copilot.data.migration.edit.xml b/.idea/copilot.data.migration.edit.xml new file mode 100644 index 0000000..8648f94 --- /dev/null +++ b/.idea/copilot.data.migration.edit.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/deploymentTargetSelector.xml b/.idea/deploymentTargetSelector.xml new file mode 100644 index 0000000..c94b700 --- /dev/null +++ b/.idea/deploymentTargetSelector.xml @@ -0,0 +1,18 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/deviceManager.xml b/.idea/deviceManager.xml new file mode 100644 index 0000000..91f9558 --- /dev/null +++ b/.idea/deviceManager.xml @@ -0,0 +1,13 @@ + + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..639c779 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..19364dc --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/migrations.xml b/.idea/migrations.xml new file mode 100644 index 0000000..f8051a6 --- /dev/null +++ b/.idea/migrations.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..952c818 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml new file mode 100644 index 0000000..16660f1 --- /dev/null +++ b/.idea/runConfigurations.xml @@ -0,0 +1,17 @@ + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/build/generated/source/buildConfig/debug/com/likesoft/mdedal/BuildConfig.java b/app/build/generated/source/buildConfig/debug/com/likesoft/mdedal/BuildConfig.java new file mode 100644 index 0000000..06c3d0d --- /dev/null +++ b/app/build/generated/source/buildConfig/debug/com/likesoft/mdedal/BuildConfig.java @@ -0,0 +1,12 @@ +/** + * Automatically generated file. DO NOT MODIFY + */ +package com.likesoft.mdedal; + +public final class BuildConfig { + public static final boolean DEBUG = Boolean.parseBoolean("true"); + public static final String APPLICATION_ID = "com.likesoft.mdedal"; + public static final String BUILD_TYPE = "debug"; + public static final int VERSION_CODE = 54; + public static final String VERSION_NAME = "2.2.2"; +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..dae0630 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/ic_new_button-web.png b/app/src/main/ic_new_button-web.png new file mode 100644 index 0000000..872cb0d Binary files /dev/null and b/app/src/main/ic_new_button-web.png differ diff --git a/app/src/main/java/com/likesoft/mdedal/Alarm.java b/app/src/main/java/com/likesoft/mdedal/Alarm.java new file mode 100644 index 0000000..6826ebd --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/Alarm.java @@ -0,0 +1,72 @@ +package com.likesoft.mdedal; + +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.os.PowerManager; + +import java.util.Calendar; + +public class Alarm extends BroadcastReceiver +{ + @Override + public void onReceive(Context context, Intent intent) + { + + Calendar cal_curr = Calendar.getInstance(); + cal_curr.getTime(); + int curr_hour = cal_curr.get(Calendar.HOUR_OF_DAY); + + int START_WAKING_HOUR = 6; + int STOP_WAKING_HOUR = 21; + + //int START_WAKING_HOUR = 0; + //int STOP_WAKING_HOUR = 24; + + Log.d("my_debug", "curr_hour: "+curr_hour); + + //Log.d("my_debug", "cal_curr: "+sdf.format( cal_curr.getTime())+", cal_start_waking: "+ sdf.format( cal_start_waking.getTime())+", cal_stop_waking: "+ sdf.format( cal_stop_waking.getTime()) ); + + if( curr_hour >= START_WAKING_HOUR && curr_hour < STOP_WAKING_HOUR ) { + PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); + PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "mDedal:Alarm"); + wl.acquire(); + + Log.d("my_debug", "Alarm, start service !"); + + // wystartuj/obudz serwis + Intent service = new Intent(context, DedalService.class); + context.startService(service); + + wl.release(); + } + } + + public void SetAlarm(Context context) + { + AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE); + Intent i = new Intent(context, Alarm.class); + PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_IMMUTABLE); + +// Resources res = getResources(); +// int values[] = res.getIntArray(R.array.pref_sync_frequency_values); + //int sleepTime =values[refreshPos]*1000; + + //long sleepTime = 1000L * 30L; // 5s + long sleepTime = 1000L * 3600L; // 1h + Log.d("my_debug", "setAlarm, sleepTime: "+sleepTime); + + am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + sleepTime, sleepTime, pi); // Millisec * Second * Minute + } + + public void CancelAlarm(Context context) + { + Intent intent = new Intent(context, Alarm.class); + PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); + alarmManager.cancel(sender); + } + +} diff --git a/app/src/main/java/com/likesoft/mdedal/AsyncCallChangeDate.java b/app/src/main/java/com/likesoft/mdedal/AsyncCallChangeDate.java new file mode 100644 index 0000000..f7ac945 --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/AsyncCallChangeDate.java @@ -0,0 +1,141 @@ +package com.likesoft.mdedal; + +import android.app.Activity; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.SharedPreferences; +import android.os.AsyncTask; +import android.preference.PreferenceManager; +import android.widget.LinearLayout; +import android.widget.Toast; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +/** +* Created by darek on 2016-01-25. +*/ +abstract class AsyncCallChangeDate extends AsyncTask { + private Activity calendarActivity; + ProgressDialog progressDialog; + String response; + String id_zlecenia; + String kod_pola; + String wartosc; + LinearLayout movingEl; + + public AsyncCallChangeDate(Activity calendarActivity, String id_zlecenia, String kod_pola, String wartosc) { + this.calendarActivity = calendarActivity; + //this.progressDialog = new ProgressDialog(); + + this.id_zlecenia = id_zlecenia; + this.kod_pola = kod_pola; + this.wartosc = wartosc; + //this.progressDialog = new ProgressDialog(); + } + + @Override + protected Void doInBackground(String... params) { + android.util.Log.d("my_debug", "doInBackground"); + DedalHttpConnection con = new DedalHttpConnection(calendarActivity.getApplicationContext()); + Map params_post = new HashMap(); + params_post.put("id_zlecenia", id_zlecenia); + params_post.put("kod_pola", kod_pola); + params_post.put("wartosc", wartosc); + response = con.sendPost("public/ajax/zmien_wartosc_zlecenie_pole_stale.php", params_post); + return null; + } + + @Override + protected void onPostExecute(Void result) { + android.util.Log.d("my_debug", "onPostExecute"); + + //this.progressDialog.dismiss(); + Log.d("CalAct", "resp: "+response); + if( response != null && "true".equals(response) ) { + + JSONObject jZlecenie = null; + try { + + // read file + Context context = calendarActivity.getApplicationContext(); + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); + File dLista = new File(prefs.getString("dir", "") + "/baza/lista.profil"); + String sJson = DedalHelper.getFileContent(dLista.getAbsolutePath()); + JSONObject jFile = new JSONObject(sJson); + + JSONObject jProfiles = jFile.getJSONObject("profile"); + Iterator keys = jProfiles.keys(); + while (keys.hasNext()) { + String id_profilu_curr = (String) keys.next(); + try { + JSONObject jProfil = jProfiles.getJSONObject(id_profilu_curr); +// if( !jProfil.has("zlecenia") || !"[]".equals(jProfil.getString("zlecenia")) ) { +// continue; +// } + JSONObject jZlecenia_local = jProfil.getJSONObject("zlecenia"); + if (!jZlecenia_local.has(id_zlecenia)) + continue; + + jZlecenie = jZlecenia_local.getJSONObject(id_zlecenia); + //change value + if (jZlecenie.has(kod_pola)) { + jZlecenie.put(kod_pola, wartosc); + Log.d("CalAct", "kod_pola: " + kod_pola + "wartosc: " + wartosc); + } + } + catch (JSONException e) { + Log.e("DEDAL", "onPostExecute", e); + } + } + + // save file + DedalHelper.putFileContent(prefs.getString("dir", "") + "/baza/lista.profil", jFile.toString()); +// Toast.makeText(CalendarActivity.this, "Uaktualniono poprawnie", +// Toast.LENGTH_LONG).show(); + + loadInputs(); +// movingEl.removeAllViews(); +// movingEl.addView(getZlecenieElement(jZlecenie, jKolumny)); + + + } catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + } + + } + else { + reloadContent(); + Toast.makeText(calendarActivity, "Wystąpił błąd podczas uaktulaniania, zmiany zostały cofnięte", + Toast.LENGTH_LONG).show(); + Log.d("CalAct", "Błąd przy połaćzeniu do zmien_wartosc_zlecenie_pole_stale.php"); + } + } + + protected abstract void reloadContent(); + + abstract public void loadInputs(); + + @Override + protected void onPreExecute() { + android.util.Log.d("my_debug", "onPreExecute"); + +// Toast.makeText(CalendarActivity.this, "Rozpoczynam uaktualnianie ...", +// Toast.LENGTH_LONG).show(); + } + + @Override + protected void onProgressUpdate(Void... values) { + android.util.Log.i("my_debug", "onProgressUpdate"); + } +} diff --git a/app/src/main/java/com/likesoft/mdedal/AutoStart.java b/app/src/main/java/com/likesoft/mdedal/AutoStart.java new file mode 100644 index 0000000..d689b94 --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/AutoStart.java @@ -0,0 +1,19 @@ +package com.likesoft.mdedal; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; + +public class AutoStart extends BroadcastReceiver +{ + Alarm alarm = new Alarm(); + @Override + public void onReceive(Context context, Intent intent) + { + if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) + { + Log.d("my_debug", "Autostart"); + alarm.SetAlarm(context); + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/likesoft/mdedal/CalendarActivity.java b/app/src/main/java/com/likesoft/mdedal/CalendarActivity.java new file mode 100644 index 0000000..5206b58 --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/CalendarActivity.java @@ -0,0 +1,1400 @@ +package com.likesoft.mdedal; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.ClipData; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Color; +import android.net.Uri; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.view.DragEvent; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MotionEvent; +import android.view.View; +import android.widget.Button; +import android.widget.HorizontalScrollView; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TableLayout; +import android.widget.TableRow; +import android.widget.TextView; +import android.widget.Toast; + +import com.likesoft.mdedal.gui.BorderLinearLayout; +import com.likesoft.mdedal.gui.BorderTextView; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; +import java.util.Comparator; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +public class CalendarActivity extends Activity { + protected Class getMainActivity() { + return MainActivity.class; + } + + private static final String DATA_KOD = "nast_wizyta_data"; + private static final String DATA_TYP_KOD = "nast_wizyta_typ"; + + private static String CALENDAR_TYPE = "tydzien"; // tydzien | miesiac + + private Calendar todayCalendar = null; + SharedPreferences prefs; + private String[] WEEK_NAMES; + private Map STATUS_COLORS = null; + private Map STATUS_NAMES = null; + private String[] STATUS_LEGEND_ORDER; + private String PROFILE_TYPE = "Kalendarz"; + + private LinearLayout lContent; + private String id_profilu = null; + private JSONObject jZlecenia = null; + private JSONArray jKolumny = null; + private JSONArray jSlady = null; + + + private int curr_page = 0; + private ArrayList columnsInRows; + + HorizontalScrollView lMainScroll=null; + ScrollView vertScroll = null; + private int mScrollDistance =0; + + public TextView tv_hour = null; + + RefreshLayoutAndThread rlat; + +// public interface OnScrollViewListener { +// public void onScrollChanged(OnScrollViewListener listener); +// } +// +// public class MyScrollView extends ScrollView { +// private OnScrollViewListener mListener; +// +// public MyScrollView(Context c) { +// super(c); +// } +// +// @Override +// protected void onScrollChanged(int l, int t, int oldl, int oldt) { +// super.onScrollChanged(l, t, oldl, oldt); +// if (mListener != null) { +// mListener.onScrollChanged((OnScrollViewListener) this); +// } +// } +// +// +// public void setOnScrollViewListener(OnScrollViewListener listener) { +// mListener = listener; +// } +// +// +// +// } + //private ArrayList rowsColumn; + @Override + protected void onCreate(Bundle savedInstanceState) { + + WEEK_NAMES = new String[7]; + WEEK_NAMES[0] = "Poniedziałek"; + WEEK_NAMES[1] = "Wtorek"; + WEEK_NAMES[2] = "Środa"; + WEEK_NAMES[3] = "Czwartek"; + WEEK_NAMES[4] = "Piątek"; + WEEK_NAMES[5] = "Sobota"; + WEEK_NAMES[6] = "Niedziela"; + + STATUS_COLORS = new HashMap(); + STATUS_COLORS.put("pierwsza_wizyta", "#FFFFFF"); + STATUS_COLORS.put("manitorowac_wplate", "#ADD8E6"); + STATUS_COLORS.put("gotowka", "#FF0000"); + STATUS_COLORS.put("ugoda", "#90EE90"); + STATUS_COLORS.put("nastepna_wizyta_negocjacje", "#ff9933"); + STATUS_COLORS.put("nastepna_wizyta", "YELLOW");//"#D3D3D3"); + STATUS_COLORS.put("pozostale", "#D3D3D3");//"#D3D3D3"); + STATUS_COLORS.put("slad", "#E6E6E6"); + + STATUS_NAMES = new HashMap(); + STATUS_NAMES.put("pierwsza_wizyta", "Pierwsza wizyta"); + STATUS_NAMES.put("manitorowac_wplate", "Monitoring wpłat"); + STATUS_NAMES.put("gotowka", "Pobiorę gotówkę"); + STATUS_NAMES.put("ugoda", "Podpiszę ugodę"); + STATUS_NAMES.put("nastepna_wizyta_negocjacje", "Negocjacje"); + STATUS_NAMES.put("nastepna_wizyta", "Wykonać następną wizytę");//Monitorować dokonane ustalenia z dłużnikiem"); + STATUS_NAMES.put("pozostale", "Pozostałe sprawy"); + STATUS_NAMES.put("slad", "Ślady"); + + STATUS_LEGEND_ORDER = new String[8]; + STATUS_LEGEND_ORDER[0] = "pierwsza_wizyta"; + STATUS_LEGEND_ORDER[1] = "manitorowac_wplate"; + STATUS_LEGEND_ORDER[2] = "gotowka"; + STATUS_LEGEND_ORDER[3] = "ugoda"; + STATUS_LEGEND_ORDER[4] = "nastepna_wizyta_negocjacje"; + STATUS_LEGEND_ORDER[5] = "nastepna_wizyta"; + STATUS_LEGEND_ORDER[6] = "pozostale"; + STATUS_LEGEND_ORDER[7] = "slad"; + + + + super.onCreate(savedInstanceState); + Context context = getApplicationContext(); + prefs = PreferenceManager.getDefaultSharedPreferences(context); + + loadJsons(); + + if( id_profilu == null ) { + Log.d("CalAct", "Brak id_profilu"); + return; + } + + if( jKolumny == null || jZlecenia == null ) { + return; + } + + //todayCalendar = new GregorianCalendar(2016,0,18,0,0,1); + todayCalendar = new GregorianCalendar(); + + + +// LinearLayout llAllWrapper = new LinearLayout(this); +// llAllWrapper.setOrientation(LinearLayout.VERTICAL); +// setContentView(llAllWrapper); + + LinearLayout lMain = new LinearLayout(this); + lMain.setOrientation(LinearLayout.VERTICAL); + //lMain.setPadding(50, 15, 15, 15); + setContentView(lMain); + + lMainScroll = new HorizontalScrollView(this); + vertScroll = new ScrollView(this); +// vertScroll.setOnScrollViewListener(new CalendarActivity.OnScrollViewListener() { +// +// public void onScrollChanged(CalendarActivity.OnScrollViewListener listener) { +// mScrollDistance = listener.getScrollY(); +// } +// }); + + lMain.setOnDragListener(new AllDragListener()); + + lMainScroll.addView(vertScroll); + //vertScroll.addView(lMain); + + LinearLayout lHeader = new LinearLayout(this); + lHeader.setOrientation(LinearLayout.VERTICAL); + lContent = new LinearLayout(this); + lContent.setOrientation(LinearLayout.VERTICAL); + + LinearLayout lContentWrapper = new LinearLayout(this); + lContentWrapper.setOrientation(LinearLayout.VERTICAL); + lContentWrapper.addView(lContent); + + + vertScroll.addView(lContentWrapper); + LinearLayout lFooter = new LinearLayout(this); + lFooter.setOrientation(LinearLayout.VERTICAL); + lContentWrapper.addView(lFooter); + + HorizontalScrollView lHeaderScroll = new HorizontalScrollView(this); + lHeaderScroll.addView(lHeader); + + lHeaderScroll.setPadding(50,10,10,10); + lContentWrapper.setPadding(50,10,10,10); + //lFooter.setPadding(50,10,10,10); + + + + lMain.addView(lHeaderScroll); + lMain.addView(lMainScroll); + //lMain.addView(lFooter); + +// lMain.addView(lHeader); +// lMain.addView(lContent); +// lMain.addView(lFooter); + + + // lMain + + drawHeader(lHeader); + drawContent(); + drawFooter(lFooter); + } + + protected void onDestroy() { + // TODO Auto-generated method stub + super.onDestroy(); + + rlat.interrupt(); + + // destroy variables + Calendar todayCalendar = null; + + WEEK_NAMES = null; + STATUS_COLORS = null; + STATUS_NAMES = null; + STATUS_LEGEND_ORDER = null; + + lContent = null; + id_profilu = null; + jZlecenia = null; + jKolumny = null; + jSlady = null; + + columnsInRows = null; + + lMainScroll=null; + vertScroll = null; + + tv_hour = null; + + Log.d("CalAct", "ondestroy"); + //onDestroyD(this); + } + + + //todo: refaktor do jednej wspolnej funkcji: + private boolean sprawdz_czy_sa_stare_wizyty(String cur_id) { + boolean ret = false; + //sprawdzić, czy istnieją przeterm + // inowane wizyty + String id = ""; + try { + // JSONObject jZlecenia= jZlecenia; //new JSONObject(jProfil.getString("zlecenia")); //roznica !!!! + Iterator keys = jZlecenia.keys(); + while (keys.hasNext()) { + + id = (String) keys.next(); + JSONObject jZlecenie = jZlecenia.getJSONObject(id); + + String status = jZlecenie.getString("status"); + String nast_wizyta_typ = jZlecenie.getString("nast_wizyta_typ"); + //przydz_odeb + if( "przydz_odeb".equals(status)){ + //nastepna_wizyta + //ugoda + //gotowka + if( "nastepna_wizyta".equals(nast_wizyta_typ) + || "ugoda".equals(nast_wizyta_typ) + || "gotowka".equals(nast_wizyta_typ)){ + //aM.add(jZlecenie);// + String nast_wizyta_data = jZlecenie.getString("nast_wizyta_data"); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Calendar cToday = new GregorianCalendar(); + String cString = sdf.format(cToday.getTime()); + if( cString.compareTo(nast_wizyta_data)>0){ + String id_zlecenia = ""+id;// + ".json"; //zmiana !!! + + if( id_zlecenia.equals(cur_id)){ //names.get(cur_id))){ + // można biezace edytować + ret = false; + break; + } + //return; + ret = true; + //break; + } + } + } + } + if( ret){ + AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); + alertDialog.setTitle( "Uwaga");//res.getString(R.string.zakanczanie_wizyty) ); + alertDialog.setMessage("Posiadasz nieprzerobione stare wizyty. Zaplanuj sprawy na kolejne dni
id zlecenia: " + id); + alertDialog.setPositiveButton("Anuluj", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int which) { + //mod_json_files(false); + dialog.dismiss(); + } + }); + alertDialog.show(); + } + + } catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + } + return ret; + } + + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.menu_calendar, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + + //noinspection SimplifiableIfStatement + if (id == R.id.action_settings) { + return true; + } + + return super.onOptionsItemSelected(item); + } + + // SET COLUMNS HEIGHT +// @Override +// public void onWindowFocusChanged(boolean hasFocus) { +// // TODO Auto-generated method stub +// super.onWindowFocusChanged(hasFocus); +// +// setColumnsHeight(); +// } + + @Override + protected void onResume() { + super.onResume(); + Log.d("CalAct", "onresume"); + drawContent(); + } + + private void loadJsons() { + try { + File dLista = new File(prefs.getString("dir", "") + "/baza/lista.profil"); + String sJson = DedalHelper.getFileContent(dLista.getAbsolutePath()); + JSONObject jFile = new JSONObject(sJson); + + JSONObject jProfiles = jFile.getJSONObject("profile"); + if( id_profilu == null ) { + id_profilu = getIdProfiluByType(jProfiles, PROFILE_TYPE); + } + if( id_profilu == null ) { + Bundle extras = getIntent().getExtras(); + if (extras != null) { + id_profilu = extras.getString("id_profilu"); + } + } + + JSONObject jProfil = jProfiles.getJSONObject(id_profilu); + jKolumny = jProfil.getJSONArray("profil_kolumny"); + jZlecenia = jProfil.getJSONObject("zlecenia"); + if( jFile.has("slady_interwencji_zlecen") ) { + jSlady = jFile.getJSONArray("slady_interwencji_zlecen"); + } + } catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + } + } + + private String getIdProfiluByType(JSONObject jProfiles, String calendar_type) { + String id_profilu = null; + try { + Iterator keys = jProfiles.keys(); + while (keys.hasNext()) { + String id_profilu_temp = (String) keys.next(); + JSONObject jProfil = jProfiles.getJSONObject(id_profilu_temp); + Log.d("CalAct", "id_profilu_temp: " + id_profilu_temp+", jProfil.getString(typ_profilu)"+jProfil.getString("typ_profilu")+", calendar_type: "+calendar_type); + if( jProfil.has("typ_profilu") && calendar_type.equals(jProfil.getString("typ_profilu")) ) { + id_profilu = id_profilu_temp; + break; + } + } + } + catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + } + return id_profilu; + } + + private void setColumnsHeight() { + + + if( columnsInRows == null || columnsInRows.size() == 0 ) { + return; + } + for( int i = 0 ; i < columnsInRows.size() ; i++ ) { + // get maximum height of exist columns + ColumnLinearLayout[] columnsInRow = columnsInRows.get(i); + int max_height = 0; + for (int j = 0; j < 7; j++) { + ColumnLinearLayout llcolumn = columnsInRow[j]; + int height = llcolumn.getColumnHeight(); + //Log.d("CalAct", "height: "+height+", max_height: "+max_height); + if ( height > max_height) { + max_height = height; + } + } + + if( max_height < 50 ) { + max_height = 50; + } + //Log.d("CalAct", "max_height: "+max_height); + // set height + for (int j = 0; j < 7; j++) { + View llcolumn = columnsInRow[j]; + + + llcolumn.setMinimumHeight(max_height); + llcolumn.setMinimumWidth(200); +// LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT); +// llcolumn.setLayoutParams(params); + } + } + } + + private void drawHeader(LinearLayout lHeader) { + lHeader.setPadding(0, 0, 0, 20); + // WYBÓR TYDZIEN / MIESIAC + LinearLayout lchangeType = new LinearLayout(this); + lHeader.addView(lchangeType); + + Button bTydzien = new Button(this); + lchangeType.addView(bTydzien); + bTydzien.setText("Tygodniowy"); + bTydzien.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + CALENDAR_TYPE = "tydzien"; + drawContent(); + } + }); + Button bMiesiac= new Button(this); + lchangeType.addView(bMiesiac); + bMiesiac.setText("Miesięczny"); + bMiesiac.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + CALENDAR_TYPE = "miesiac"; + drawContent(); + } + }); + + // separate + TextView tv = new TextView(this); + tv.setText(" | "); + lchangeType.addView(tv); + + // PAGOWANIE + Button bPrev = new Button(this); + lchangeType.addView(bPrev); + bPrev.setText("Poprzednia"); + bPrev.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + curr_page--; + drawContent(); + } + }); + Button bNext = new Button(this); + lchangeType.addView(bNext); + bNext.setText("Następna"); + bNext.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + curr_page++; + drawContent(); + } + }); + + // GODZINA PODCZAS PRZESOWANIA + tv_hour = new TextView(this); + tv_hour.setPadding(5,0,0,10); + lchangeType.addView(tv_hour); + + // REFRESH BUTTON + rlat = new RefreshLayoutAndThread(this) { + @Override + protected void whenThreadNeedToReaoad() { + loadJsons(); + drawContent(); + } + + @Override + protected void setLastGPSInfo_abstr() { + + } + }; + LinearLayout refreshLayout = rlat.getRefreshLayout(); + refreshLayout.setPadding(10, 0, 0, 0); + lchangeType.addView(refreshLayout); + TextView textUpload = rlat.getTextUpload(); + lchangeType.addView(textUpload); + rlat.setLastUpdateInfo(); + rlat.start(); + + + // NAGŁÓWKI + LinearLayout lnaglowki = new LinearLayout(this); + lHeader.addView(lnaglowki); + TextView tnaglowki = new TextView(this); + lnaglowki.addView(tnaglowki); + String snaglowki = ""; + for( int i = 0 ; i < jKolumny.length() ; i++ ) { + try { + if( i > 0 ) { + snaglowki += " | "; + } + JSONObject jKolumna = jKolumny.getJSONObject(i); + if(jKolumna.has("nazwa")) { + snaglowki += jKolumna.getString("nazwa"); + } + } catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + } + } + tnaglowki.setText(snaglowki); + } + + private void drawFooter(LinearLayout lFooter) { + TextView tlegend_title = new TextView(this); + tlegend_title.setText("Legenda"); + lFooter.addView(tlegend_title); + lFooter.setPadding(0,20,0,0); + + LinearLayout llegend = new LinearLayout(this); + lFooter.addView(llegend); + Log.d("CalAct", "drawFooter"); + for (int i = 0 ; i < STATUS_LEGEND_ORDER.length ; i++){ + + String status = STATUS_LEGEND_ORDER[i]; + String status_name = STATUS_NAMES.get(STATUS_LEGEND_ORDER[i]); + Log.d("CalAct", "status: "+status+", status_name: "+status_name); + BorderTextView btw = new BorderTextView(this); + llegend.addView(btw); + btw.setText(status_name); + btw.setPadding(10, 10, 10, 10); + if( STATUS_COLORS.get(status) != null ) { + btw.setBackgroundColor(Color.parseColor(STATUS_COLORS.get(status))); + }else{ + btw.setBackgroundColor(Color.parseColor(STATUS_COLORS.get("pozostale"))); + } + } + } + + private void drawContent() { + Log.d("CalAct", "drawContent"); + //(new Exception()).printStackTrace(); + columnsInRows = new ArrayList(); + + lContent.removeAllViews(); + + GregorianCalendar cDate = (GregorianCalendar)todayCalendar.clone(); + if( curr_page != 0 ) { + cDate.add(Calendar.DATE, curr_page * 7); +// if( "tydzien".equals(CALENDAR_TYPE) ) { +// cDate.add(Calendar.DATE, curr_page * 7); +// } +// else if ( "miesiac".equals(CALENDAR_TYPE) ) { +// cDate.add(Calendar.MONTH, curr_page); +// } + + } + ArrayList week_package = new ArrayList(); + if( "tydzien".equals(CALENDAR_TYPE) ) { +// String[] week_day_dates = getWeekDayDates(cDate); +// week_package.add(week_day_dates); + //week_package = getWeeksWeeks(); + week_package = getWeeksForTable(cDate, 0, 1); + } + else if ( "miesiac".equals(CALENDAR_TYPE) ) { + //week_package = getMonthWeeks(cDate); + week_package = getWeeksForTable(cDate, 1, 3); + } + + TableLayout tL = new TableLayout(this); + lContent.addView(tL); + // tL.setStretchAllColumns(false); + + + for( int i = 0 ; i < week_package.size() ; i++ ) { + drawOneWeekTable(week_package.get(i), tL); + } + + lContent.post(new Runnable() { + @Override + public void run() { + setColumnsHeight(); + } + }); + } + + private void drawOneWeekTable(String[] week_day_dates, TableLayout tL) { + + String[] tab_kolumuny_nazwy = new String[7]; + for( int i = 0 ; i < week_day_dates.length ; i++ ) { + tab_kolumuny_nazwy[i] = WEEK_NAMES[i] + "\n" + week_day_dates[i]; + } + + + TableRow tRHead = new TableRow(this); + + tL.addView(tRHead); + tRHead.setBackgroundColor(Color.LTGRAY); + for( int i = 0 ; i < tab_kolumuny_nazwy.length ; i++ ) { + TextView tV = new TextView(this); + tV.setText(tab_kolumuny_nazwy[i]); + tRHead.addView(tV); + } + + // CONTENT + TableRow tRContent = new TableRow(this); + tL.addView(tRContent); + SimpleDateFormat sdf_full = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + String cTodayString = sdf.format(todayCalendar.getTime()); + ColumnLinearLayout[] columnsInRow = new ColumnLinearLayout[7]; + columnsInRows.add(columnsInRow); + for( int i = 0 ; i < tab_kolumuny_nazwy.length ; i++ ) { + ColumnLinearLayout llColumn = new ColumnLinearLayout(this, Color.parseColor("#CC7000")); + + //llColumn.setLayoutParams(new LinearLayout.LayoutParams(200, LinearLayout.LayoutParams.WRAP_CONTENT));//TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); + + + columnsInRow[i] = llColumn; + llColumn.setOrientation(LinearLayout.VERTICAL); + //llColumn.setMinimumHeight(50); + + llColumn.setOnDragListener(new MyDragColumnListener()); + + llColumn.setDate(week_day_dates[i]); + tRContent.addView(llColumn); + + boolean is_today = false; + if( cTodayString.equals(week_day_dates[i]) ) { + is_today = true; + } + + ArrayList> sortedKeys = getSortedKeysFromJZlecenia(jZlecenia, jSlady); + + //Iterator keys = jZlecenia.keys(); + //while (keys.hasNext()) { + for( int j = 0 ; j < sortedKeys.size() ; j++ ) { + try { + HashMap temp = sortedKeys.get(j); + + String id_zlecenia = temp.get("id_zlecenia"); //(String) keys.next(); + String typ = temp.get("typ"); + if( "zlecenie".equals(typ) ) { + //Log.d("my_debug", "kalendarz, id_zlecenia: "+id_zlecenia); + if (!jZlecenia.has(id_zlecenia)) { + continue; + } + JSONObject jZlecenie = jZlecenia.getJSONObject(id_zlecenia); + + boolean show_zlecenie = false; + String zl_data_typ = jZlecenie.getString(DATA_TYP_KOD); + String zl_data = jZlecenie.getString(DATA_KOD); + if (zl_data == null || "".equals(zl_data) || "null".equals(zl_data)) { // jZlecenie.getString(DATA_KOD) == "null" ) { +// if( is_today ) { +// show_zlecenie = true; +// } + } else { + if (!"odmowa".equals(zl_data_typ)) { + Calendar cal = Calendar.getInstance(); + cal.setTime(sdf_full.parse(zl_data));// all done + if (week_day_dates[i].equals(sdf.format(cal.getTime()))) { + show_zlecenie = true; + } + } + } + + if (show_zlecenie) { + LinearLayout zl_wrapper = new LinearLayout(this); + zl_wrapper.setOrientation(LinearLayout.VERTICAL); + zl_wrapper.setId(Integer.parseInt(id_zlecenia)); + zl_wrapper.setOnTouchListener(new MyTouchListener()); + llColumn.addView(zl_wrapper); + + LinearLayout zl = getZlecenieElement(jZlecenie, jKolumny); + zl_wrapper.addView(zl); + zl_wrapper.setLayoutParams(new LinearLayout.LayoutParams(200, LinearLayout.LayoutParams.WRAP_CONTENT));//TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); + } + } + else if( "slad".equals(typ) ) { + boolean show_zlecenie = false; + + String data = temp.get("data"); + Calendar cal = Calendar.getInstance(); + cal.setTime(sdf_full.parse(data));// all done + if (week_day_dates[i].equals(sdf.format(cal.getTime()))) { + //if (week_day_dates[i].equals(temp.get("data")) ) { + show_zlecenie = true; + + if (show_zlecenie) { + LinearLayout zl_wrapper = new LinearLayout(this); + zl_wrapper.setOrientation(LinearLayout.VERTICAL); + zl_wrapper.setId(Integer.parseInt(id_zlecenia)); + zl_wrapper.setOnTouchListener(new MyTouchListener()); + llColumn.addView(zl_wrapper); + + //LinearLayout zl = new LinearLayout(this); + LinearLayout zl = getSladElement(id_zlecenia, temp.get("nr_sprawy")); + zl_wrapper.addView(zl); + zl_wrapper.setLayoutParams(new LinearLayout.LayoutParams(200, LinearLayout.LayoutParams.WRAP_CONTENT)); + } + } + } + + } catch (JSONException e) { + e.printStackTrace(); + } catch (ParseException e) { + e.printStackTrace(); + } + } + } + + } + + private ArrayList getSortedKeysFromJZlecenia(JSONObject jZlecenia, JSONArray jSlady) { + //ArrayList forSortKeys = new ArrayList(); + ArrayList> forSortKeys = new ArrayList>(); + Iterator keys = jZlecenia.keys(); + + // create ArrayList which object to sort + while (keys.hasNext()) { + try { + HashMap temp = new HashMap(); + String id_zlecenia = (String) keys.next(); + JSONObject jZlecenie = jZlecenia.getJSONObject(id_zlecenia); + String dateNextWiz = "0000-00-00 00:00:00"; + if( jZlecenie.has(DATA_KOD) && !"".equals(jZlecenie.getString(DATA_KOD)) && !"null".equals(jZlecenie.getString(DATA_KOD)) ) { + dateNextWiz = jZlecenie.getString(DATA_KOD); + if ( dateNextWiz.indexOf(":") < 0 ) { // jesli nie występuje ":" to znaczy że nie ma godziny i trzeba dopisać zera aby dobrze porównywało + dateNextWiz += " 00:00:00"; + } + } + String keyForSort = dateNextWiz+"_"+id_zlecenia; + temp.put("key_for_sort", keyForSort); + temp.put("typ", "zlecenie"); + forSortKeys.add(temp); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + if( jSlady != null ) { + for (int i = 0; i < jSlady.length(); i++) { + try { + JSONObject obj = jSlady.getJSONObject(i); + HashMap temp = new HashMap(); + temp.put("key_for_sort", obj.getString("data") + "_" + obj.getString("id_zlecenia")); + temp.put("typ", "slad"); + temp.put("nr_sprawy", obj.getString("nr_sprawy")); + temp.put("data", obj.getString("data")); + forSortKeys.add(temp); + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + + // sorting + Collections.sort(forSortKeys, new Comparator>() { + @Override + public int compare(HashMap left, HashMap right) { + return left.get("key_for_sort").compareTo(right.get("key_for_sort")); + } + }); + + ArrayList> sorted_id_zlecen = new ArrayList>(); + // remove date from sorted object. Just id_zlecenia is needed + for( int i = 0 ; i < forSortKeys.size() ; i++ ) { + HashMap temp = forSortKeys.get(i); + String keyForSort = temp.get("key_for_sort"); + String[] parts = keyForSort.split("_"); + if( parts.length > 1 ) { + //sorted_id_zlecen.add(parts[1]); + HashMap temp2 = new HashMap(); + temp2.put("id_zlecenia", parts[1]); + temp2.put("nr_sprawy", temp.get("nr_sprawy")); + temp2.put("typ", temp.get("typ")); + if( temp.get("data") != null ) { + temp2.put("data", temp.get("data")); + } + sorted_id_zlecen.add(temp2); + } + + //sortedKeys.get(i) = parts[0] + //sortedKeys.add(i, parts[0]); + } + + return sorted_id_zlecen; + } + + private LinearLayout getZlecenieElement(JSONObject jZlecenie, JSONArray jKolumny) { + BorderLinearLayout zl = new BorderLinearLayout(this); + + zl.setOrientation(LinearLayout.VERTICAL); + + String id_zlecenia = ""; + try { + id_zlecenia = jZlecenie.getString("id_zlecenia"); + + } catch (JSONException e) { + e.printStackTrace(); + } + + boolean first = true; + String contentText = ""; + for( int i = 0 ; i < jKolumny.length() ; i++ ) { + try { + JSONObject jkolumna = jKolumny.getJSONObject(i); + String kod = jkolumna.getString("kod"); + String nazwa = jkolumna.getString("nazwa"); + + contentText += DedalHelper.getValueFromKod(kod, jZlecenie); + + if( ( i % 3 == 2 ) || i == jKolumny.length() - 1 ) { + LinearLayout row = new LinearLayout(this); + row.setPadding(5,1,5,1); + zl.addView(row); + TextView tv = new TextView(this); + tv.setText(contentText); + tv.setTextAppearance(this, R.style.OpisTextLista); + contentText = ""; + row.addView(tv); + if(first) { + row.setOnClickListener(new OnclickStartMainActivity(id_zlecenia)); + first = false; + } + } + else { + contentText += " | "; + } + + + +// if( i > 0 ) { +// contentText += " | "; +// if (i % 3 == 0) { +// contentText += "\n"; +// } +// } + + } catch (JSONException e) { + e.printStackTrace(); + } + } + + // get typ and set color + + String zlecenieColor = getZlecenieColor(jZlecenie); + zl.setBackgroundColor(Color.parseColor(zlecenieColor)); + + //zl.setText(contentText); + return zl; + } + + private LinearLayout getSladElement(String id_zlecenia, String nr_sprawy) { + BorderLinearLayout zl = new BorderLinearLayout(this); + zl.setOrientation(LinearLayout.VERTICAL); + zl.setPadding(10,5,10,5); + + TextView tv = new TextView(this); + tv.setText(nr_sprawy); + tv.setTextColor(Color.DKGRAY); + tv.setTextAppearance(this, R.style.OpisTextLista); + + zl.setOnClickListener(new OnclickStartMainActivity(id_zlecenia)); + zl.addView(tv); + zl.setBackgroundColor(Color.parseColor(STATUS_COLORS.get("slad"))); + return zl; + } + + private String getZlecenieColor(JSONObject jZlecenie) { + String color = "#000000"; + if( jZlecenie.has(DATA_TYP_KOD) ) { + try { + String status = jZlecenie.getString(DATA_TYP_KOD); + if( status == null || "null".equals(status) || "".equals(status) ) { + status = "pierwsza_wizyta"; + } + if( STATUS_COLORS.get(status) != null ) { + //zl.setBackgroundColor(Color.parseColor(STATUS_COLORS.get(status))); + color = STATUS_COLORS.get(status); + }else{ + //zl.setBackgroundColor(Color.parseColor(STATUS_COLORS.get("pozostale"))); + color = STATUS_COLORS.get("pozostale"); + } + if( jZlecenie.has("status")) { + String status_zlecenia = jZlecenie.getString("status"); + if( !status_zlecenia.equals("przydz_odeb") && !status_zlecenia.equals("przydz_nie_odeb") && !status_zlecenia.equals("wykonane") ){ + //zl.setBackgroundColor(Color.parseColor(STATUS_COLORS.get("pozostale"))); + color = STATUS_COLORS.get("pozostale"); + } + } + + } catch (JSONException e) { + e.printStackTrace(); + } + } + return color; + } + + private String[] getWeekDayDates(Calendar c_date) { + String[] week_day_dates = new String[7]; + + int week_day = c_date.get(Calendar.DAY_OF_WEEK); //1 - niedziela, 2 - poniedziałek, ... + week_day = week_day - 1; //0 - niedziela, 1 - poniedziałek, ... + Log.d("my_debug", "week_day: "+week_day); + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + for ( int i = 0 ; i < 7 ; i++ ) { + Calendar c_date_now = (Calendar)c_date.clone(); + int ip = i + 1; + int diff_days = ip - week_day; + c_date_now.add(Calendar.DATE, diff_days); + + week_day_dates[i] = sdf.format(c_date_now.getTime()); + } + + return week_day_dates; + } + + private ArrayList getWeeksForTable(GregorianCalendar c_date, int NUM_PREV_WEEKS, int NUM_NEXT_WEEKS) { + ArrayList week_package = new ArrayList(); + +// int NUM_PREV_WEEKS = 1; +// int NUM_NEXT_WEEKS = 3; + + GregorianCalendar d = (GregorianCalendar)c_date.clone(); + d.add(Calendar.DATE, -7 * NUM_PREV_WEEKS); + for( int i = 0 ; i < NUM_PREV_WEEKS + NUM_NEXT_WEEKS + 1 ; i++ ) { + String[] array_week_dates = getWeekDayDates(d); + week_package.add(i, array_week_dates); + d.add(Calendar.DATE, 7); + } + + + ///////////////// +// int curr_month = c_date.get(Calendar.MONTH); +// int curr_year = c_date.get(Calendar.YEAR); +// +// GregorianCalendar d = new GregorianCalendar(curr_year, curr_month, 1); +// +// for( int i = 0 ; i < 6 ; i++ ) { +// +// try { +// String[] array_week_dates = getWeekDayDates(d); +// +// GregorianCalendar first = new GregorianCalendar(); +// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); +// first.setTime(sdf.parse(array_week_dates[0])); +// +// GregorianCalendar last = new GregorianCalendar(); +// last.setTime(sdf.parse(array_week_dates[array_week_dates.length - 1])); +// +// if ( i > 0 && first.get(Calendar.MONTH) != curr_month && last.get(Calendar.MONTH) != curr_month ) { +// break; +// } +// Log.d("CalAct", "getMonthWeeks, "+array_week_dates[0]); +// week_package.add(i, array_week_dates); +// d.add(Calendar.DATE, 7); +// +// } catch (ParseException e) { +// e.printStackTrace(); +// } +// } + + return week_package; + } + + private final class MyTouchListener implements View.OnTouchListener { + + @Override + public boolean onTouch(View view, MotionEvent motionEvent) { + if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { + ClipData data = ClipData.newPlainText("", ""); + View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view); + view.startDrag(data, shadowBuilder, view, 0); + rlat.pauseThread = true; + + return true; + } else { + return false; + } + } + } + + class MyDragColumnListener implements View.OnDragListener { + + public MyDragColumnListener() { + + } + + private String ConvertPosToHour(int y, int max_height) { + int MIN_HOUR = 7; + int MAX_HOUR = 19; + + int hours_mins = (MAX_HOUR - MIN_HOUR) * 60; + + String godzina = null; + float proc = 0; + if( max_height > 0 ) { + proc = (float)y / max_height; + int mins_from_start = (int)(hours_mins * proc); + int hours_from_start = mins_from_start / 60; + + int mins = mins_from_start - hours_from_start * 60; + int hour = MIN_HOUR + hours_from_start; + + godzina = String.format("%02d", hour) + ":" + String.format("%02d", mins) ; + + //Log.d("CalAct", "mins_from_start: " + mins_from_start); + + } + //Log.d("CalAct", "Godzina, y: " + y + ", max_height: " + max_height+", proc: "+proc); + + //godzina = proc+""; + return godzina; + } + + @Override + public boolean onDrag(View onDropEl, DragEvent event) { + int action = event.getAction(); + try { + LinearLayout movingEl = (LinearLayout) event.getLocalState(); + ColumnLinearLayout onDropEl_ = (ColumnLinearLayout) onDropEl; + ColumnLinearLayout fromDragEl = (ColumnLinearLayout) movingEl.getParent(); + + int id_moving = movingEl.getId(); // id_moving to id_zlecenia + String date_from = fromDragEl.getDate(); + String id_drop = onDropEl_.getDate(); + String date_drop = onDropEl_.getDate(); + + //View dropZoneView = onDropEl; + + int max_height = onDropEl_.getHeight(); + int y = 0; + double proc = 0; + String godzina = null; + switch (event.getAction()) { + case DragEvent.ACTION_DRAG_STARTED: + // do nothing + break; + case DragEvent.ACTION_DRAG_ENTERED: + //onDropEl.setBackgroundColor(color_entered); + break; + case DragEvent.ACTION_DRAG_EXITED: + //onDropEl.setBackgroundColor(color_exited); + break; + case DragEvent.ACTION_DROP: + String id_zlecenia = id_moving + ""; + String status_wizyty_zlecenia = ""; + String status_zlecenia = ""; + + try { + JSONObject jZlecenie = jZlecenia.getJSONObject(id_zlecenia); + status_zlecenia = jZlecenie.getString("status"); + status_wizyty_zlecenia = jZlecenie.getString(DATA_TYP_KOD); + } catch (JSONException e) { + e.printStackTrace(); + } + + + y = Math.round(onDropEl.getY())+Math.round(event.getY()); + godzina = ConvertPosToHour(y, max_height); + tv_hour.setText(""); + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + String cTodayString = sdf.format(todayCalendar.getTime()); + //is dropable + + String date_drop_no_hour = date_drop; + if( godzina != null ) { + date_drop = date_drop +" " + godzina + ":00"; + } + + JSONObject jZlecenie = null; + String data_obslugi = null; + try { + + if (jZlecenia.has(id_zlecenia)) { + jZlecenie = jZlecenia.getJSONObject(id_zlecenia); + data_obslugi = jZlecenie.getString("data_obslugi"); + } + } catch (JSONException e) { + e.printStackTrace(); + } + + + boolean can_drop = true; + String date_drop_no_time = DedalHelper.datetime2date(date_drop); + + String wrong_status_message = "Zlecenie NIE zostało przeniesione. Nie można przenosić zleceń które mają status inny niż 'Pierwsza wizyta' oraz 'Wykonać następną wizytę'"; + if( !date_from.equals(date_drop_no_time) ) { + if (!"null".equals(status_wizyty_zlecenia) && !"".equals(status_wizyty_zlecenia) && !"pierwsza_wizyta".equals(status_wizyty_zlecenia) && !"nastepna_wizyta".equals(status_wizyty_zlecenia)) { + Toast.makeText(CalendarActivity.this, wrong_status_message, + Toast.LENGTH_LONG).show(); + can_drop = false; + } else if (jZlecenie.has("status") + && !status_zlecenia.equals("przydz_odeb") && !status_zlecenia.equals("przydz_nie_odeb") && !status_zlecenia.equals("wykonane")) { + Toast.makeText(CalendarActivity.this, wrong_status_message, + Toast.LENGTH_LONG).show(); + can_drop = false; + } + else if (cTodayString.compareTo(date_drop_no_hour) > 0) { + Toast.makeText(CalendarActivity.this, "Zlecenie NIE zostało przeniesione. Nie można przenosić zleceń na datę wsteczną", + Toast.LENGTH_LONG).show(); + can_drop = false; + } else if (data_obslugi != null && date_drop.compareTo(data_obslugi) > 0) { + Toast.makeText(CalendarActivity.this, "Zlecenie NIE zostało przeniesione. Nie można przenosić zleceń na datę przekraczającą datę obsługi: " + data_obslugi, + Toast.LENGTH_LONG).show(); + can_drop = false; + } + } + + if( can_drop ) { + //////////////MODYFIKOWANIE OBIEKTU JZLECENIA///////////////////// + try { + if ( jZlecenia.has(id_zlecenia) ) { + //change value + if (jZlecenie.has(DATA_KOD)) { + jZlecenie.put(DATA_KOD, date_drop); + //Log.d("CalAct", "kod_pola: " + kod_pola + "wartosc: " + wartosc); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + ////////////////////////////////// + + drawContent(); + + // set height + lContent.post(new Runnable() { + @Override + public void run() { + setColumnsHeight(); + } + }); + + + //run update to server + AsyncCallChangeDate task = new AsyncCallChangeDate(CalendarActivity.this, id_moving + "", DATA_KOD, date_drop) { + @Override + protected void reloadContent() { + //Log.d("CalAct", "reloadContent"); + + loadJsons(); + drawContent(); + } + + @Override + public void loadInputs() { + loadJsons(); + } + }; // week_day_dates[id_drop]); + task.execute(); + + rlat.pauseThread = false; + } + //} + break; + case DragEvent.ACTION_DRAG_ENDED: + //v.setBackgroundDrawable(normalShape); + break; + case DragEvent.ACTION_DRAG_LOCATION: + y = Math.round(onDropEl.getY())+Math.round(event.getY()); + godzina = ConvertPosToHour(y, max_height); + //dragging_view.setBackgroundColor(Color.RED); + tv_hour.setText("Ustaw na godzinę: " + godzina); + //Log.d("CalAct", "Godzina: "+godzina); + return false; + + // break; + default: + break; + } + } catch (NullPointerException e) { + e.printStackTrace(); + } + return true; + + } + } + + class AllDragListener implements View.OnDragListener { + + public AllDragListener() { + + } + + @Override + public boolean onDrag(View onDropEl, DragEvent event) throws NullPointerException{ + int action = event.getAction(); + + View dropZoneView = onDropEl; + + switch (event.getAction()) { + case DragEvent.ACTION_DRAG_STARTED: + // do nothing + break; + case DragEvent.ACTION_DRAG_ENTERED: + //onDropEl.setBackgroundColor(color_entered); + break; + case DragEvent.ACTION_DRAG_EXITED: + //onDropEl.setBackgroundColor(color_exited); + break; + case DragEvent.ACTION_DROP: + rlat.pauseThread = false; + break; + case DragEvent.ACTION_DRAG_ENDED: + //v.setBackgroundDrawable(normalShape); + break; + case DragEvent.ACTION_DRAG_LOCATION: + + // ScrollView mainScrollView = vertScroll;//(ScrollView) findViewById(R.id.main_scroll); +// +// int topOfDropZone = dropZoneView.getTop(); +// int bottomOfDropZone = dropZoneView.getBottom(); +// +// int scrollY = Math.round(event.getY());// mainScrollView.getScrollY(); +// int scrollViewHeight = mainScrollView.getMeasuredHeight(); +// +// Log.d("my_debug","location: Scroll Y: "+ scrollY + " Scroll Y+Height: "+(scrollY + scrollViewHeight)); +// Log.d("my_debug"," top: "+ topOfDropZone +" bottom: "+bottomOfDropZone); +// +// +// if (scrollY>350){ //(bottomOfDropZone > (scrollY + scrollViewHeight - 100)) { +// Log.d("my_debug"," do dolu skroluj bottomOfDropZone: "+ bottomOfDropZone); +// mainScrollView.smoothScrollBy(0, 30); +// } +// +// if (scrollY<100){ //(topOfDropZone < (scrollY + 100)){ +// Log.d("my_debug"," do gory skroluj topOfDropZone: "+ topOfDropZone); +// mainScrollView.smoothScrollBy(0, -30); +// } + + //int y = Math.round(event.getY()); + int y = Math.round(onDropEl.getY())+Math.round(event.getY()); + + mScrollDistance = vertScroll.getScrollY(); + int translatedY = y - mScrollDistance; +// Log.d("my_debug"," translatedY: "+ y); + int threshold = 50; + // make a scrolling up due the y has passed the threshold + if (translatedY < threshold) { + // make a scroll up by 30 px +// Log.d("my_debug"," do gory skroluj translatedY: "+ translatedY); +// Log.d("my_debug"," Y: "+ y); +// Log.d("my_debug"," mScrollDistance: "+ mScrollDistance); + vertScroll.scrollBy(0, -30); + } + // make a autoscrolling down due y has passed the 500 px border + if (translatedY + threshold > 500) { + // make a scroll down by 30 px +// Log.d("my_debug"," do dolu skroluj translatedY: "+ translatedY); +// Log.d("my_debug"," Y: "+ y); +// Log.d("my_debug"," mScrollDistance: "+ mScrollDistance); + vertScroll.scrollBy(0, 30); + } + + + break; + default: + break; + } + return true; + } + + } + + private class ColumnLinearLayout extends BorderLinearLayout { + + private String date = null; + //private Integer rowId = null; + + public ColumnLinearLayout(Context context) { + super(context); + } + public ColumnLinearLayout(Context context, int color) { + super(context, color); + } + + public void setDate(String date) { + this.date = date; + } + public String getDate() { + return this.date; + } + + public int getColumnHeight() { + int height = 0; + int childcount = getChildCount(); + + for (int i=0; i < childcount; i++){ + View v = getChildAt(i); + //Log.d("CalAct", "date: "+this.date+", v.id: "+v.getId()+", v.height: "+v.getHeight()); + height += v.getHeight(); + } + //height = getHeight(); + return height; + } + } + + private class OnclickStartMainActivity implements View.OnClickListener { + + private final String id_zlecenia; + + public OnclickStartMainActivity(String id_zlecenia) { + this.id_zlecenia = id_zlecenia; + } + + @Override + public void onClick(View v) { + //v.getBackg + + + v.setBackgroundColor(Color.parseColor("#FF6666")); + + + + boolean ret = sprawdz_czy_sa_stare_wizyty(id_zlecenia); + + if( ret) { + //STATUS_COLORS.put("nastepna_wizyta", "#D3D3D3"); + // if( STATUS_COLORS.containsKey()) + String zlecenieColor = "#FFFFFF"; + if( jZlecenia.has(id_zlecenia) ) { + try { + JSONObject jZlecenie = jZlecenia.getJSONObject(id_zlecenia); + zlecenieColor = getZlecenieColor(jZlecenie); + } catch (JSONException e) { + e.printStackTrace(); + } + } + v.setBackgroundColor(Color.parseColor(zlecenieColor)); + + return; + } + + + Log.d("CalAct", "Start: MainActivity"); + Intent intent = new Intent(CalendarActivity.this, MainActivity.class);//getMainActivity()); + File f = new File(prefs.getString("dir", "") + + "/baza/" + id_zlecenia+".json"); + Uri u = Uri.fromFile(f); + intent.setData(u); + intent.putExtra("filename", id_zlecenia+".json"); + if ( intent != null ) { // obsługa nulla + startActivity(intent); + } // obsługa nulla + } + } +} diff --git a/app/src/main/java/com/likesoft/mdedal/DatePickerFragment.java b/app/src/main/java/com/likesoft/mdedal/DatePickerFragment.java new file mode 100644 index 0000000..3c1d60c --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/DatePickerFragment.java @@ -0,0 +1,122 @@ +package com.likesoft.mdedal; + +import android.app.Activity; +import android.app.DatePickerDialog; +import android.app.Dialog; +import android.app.DialogFragment; +import android.os.Bundle; +import android.widget.DatePicker; +import android.widget.TextView; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.GregorianCalendar; + +/** +* Created by darek on 2016-01-25. +*/ +public class DatePickerFragment extends DialogFragment + implements DatePickerDialog.OnDateSetListener { + + public Integer nr_zlecenia; + public Activity act; + public String data_walidacja_do = null; + public TextView tv = null; + + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + // Use the current date as the default date in the picker + final Calendar c = Calendar.getInstance(); + int year = c.get(Calendar.YEAR); + int month = c.get(Calendar.MONTH); + int day = c.get(Calendar.DAY_OF_MONTH); + + // - jawne tworzenie obiektu - żeby przed return dodać DatePickerMode + // Create a new instance of DatePickerDialog and return it + DatePickerDialog dDlg = new DatePickerDialog(getActivity(), this, year, month, day); + dDlg.getDatePicker().setCalendarViewShown(true); // - false -> true + dDlg.getDatePicker().setSpinnersShown(false); // - cała linijka + return dDlg; + // + } + + + public void onDateSet(DatePicker view, int year, int month, int day) { + // Do something with the date chosen by the user + + + Log.d("my_debug", "Wybrano edycje daty wizyty nr: " + nr_zlecenia + " nowy rok: " + year); + + Calendar c = new GregorianCalendar(year, month, day); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + String date_string = sdf.format(c.getTime()); + //tv.setText(date_string); + + TimePickerFragment newFragment_time = new TimePickerFragment(); + newFragment_time.act = act; + newFragment_time.nr_zlecenia = nr_zlecenia; + newFragment_time.data_walidacja_do = data_walidacja_do; + newFragment_time.tv = tv; + newFragment_time.setDate = c; + + newFragment_time.show(getFragmentManager(), "timePicker"); + + + + + // ListActivity.this.finish(); +// final Intent intent = new Intent(); +// intent.setAction("blah"); +// getActivity().sendBroadcast(intent); +// dismiss(); + +/* + Calendar c = new GregorianCalendar(year, month, day); + Calendar cToday = new GregorianCalendar(); + + Calendar data_walidacja_do_cal = null; + if( data_walidacja_do != null ) { + try { + data_walidacja_do_cal = Calendar.getInstance(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + data_walidacja_do_cal.setTime(sdf.parse(data_walidacja_do));// all done + } catch (ParseException e) { + e.printStackTrace(); + } + } + + + if( cToday.compareTo(c)>0){ + Toast.makeText(act.getApplicationContext(), + "Nie można wybrać daty wstecznej dla wizyty nr: " + nr_zlecenia, + Toast.LENGTH_LONG).show(); + } + else if( data_walidacja_do_cal != null && c.compareTo(data_walidacja_do_cal)>0 ) { + Toast.makeText(act.getApplicationContext(), + "Nie można wybrać daty przekraczającej datę obsługi: " + data_walidacja_do, + Toast.LENGTH_LONG).show(); + } + else { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + String cString = sdf.format(c.getTime()); + + AsyncCallChangeDate task = new AsyncCallChangeDate(act, nr_zlecenia + "", DATA_KOD, cString) { + @Override + protected void reloadContent() { + // drawContent(); + final Intent intent = new Intent(); + intent.setAction("blah"); + getActivity().sendBroadcast(intent); + dismiss(); + } + + @Override + public void loadInputs() { + // loadJsons(); + } + }; // week_day_dates[id_drop]); + task.execute(); + } + */ + } +} diff --git a/app/src/main/java/com/likesoft/mdedal/DedalActivity.java b/app/src/main/java/com/likesoft/mdedal/DedalActivity.java new file mode 100644 index 0000000..d6252d6 --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/DedalActivity.java @@ -0,0 +1,4803 @@ +package com.likesoft.mdedal; + +import android.app.ActionBar.LayoutParams; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.DatePickerDialog; +import android.app.Dialog; +import android.app.TimePickerDialog; +import android.app.TimePickerDialog.OnTimeSetListener; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; +import android.content.res.Resources; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.Color; +import android.graphics.Typeface; +import android.net.Uri; +import android.os.StrictMode; +import android.provider.MediaStore; +import androidx.core.content.FileProvider; +import android.text.Editable; +import android.text.Html; +import android.text.InputType; +import android.text.TextUtils; +import android.text.TextWatcher; +import android.view.Menu; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.View.OnFocusChangeListener; +import android.view.ViewGroup; +import android.webkit.WebView; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemSelectedListener; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.DatePicker; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.RadioButton; +import android.widget.RadioGroup; +import android.widget.ScrollView; +import android.widget.Spinner; +import android.widget.TableLayout; +import android.widget.TableRow; +import android.widget.TextView; +import android.widget.TimePicker; + +import com.likesoft.mdedal.gui.BorderLinearLayout; +import com.likesoft.mdedal.gui.BorderTextView; +import com.likesoft.mdedal.gui.ButtonDate; +import com.likesoft.mdedal.gui.MLinearLayout; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileDescriptor; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +//import android.util.Log; +/** + * Created by darek on 2016-01-10. + */ +public abstract class DedalActivity extends Activity { + + + protected static final boolean isGrey = false; + protected static final int REQUEST_CODE = 10; + + + public static String STRUCT_TYP_DANYCH = "typ_danych"; + public static String STRUCT_OPCJE = "opcje"; + public static String STRUCT_OPIS = "opis"; + public static String STRUCT_WARTOSC = "wartosc"; + public static String STRUCT_KLIENT = "klient"; + public static String STRUCT_STATUS = "status"; + public static String STRUCT_CHILDS = "childs"; + public static String STRUCT_POWTARZALNY = "powtarzalny"; + public static String STRUCT_WALIDACJA = "walidacja"; + public static String STRUCT_WIERSZ_SZABLONU = "id_wiersz_szablonu"; + + // values for: STRUCT_TYP_DANYCH + public static String TYPE_TEXT = "tekst"; + public static String TYPE_TEXTBOX = "tekstbox"; + public static String TYPE_KWOTA = "kwota"; + public static String TYPE_LICZBA = "liczba"; + public static String TYPE_KOLUMNA = "kolumna"; + public static String TYPE_CHECK = "check"; + public static String TYPE_DATA = "data"; + public static String TYPE_WYBOR = "wybor"; + public static String TYPE_LISTA = "lista"; + public static String TYPE_RADIOLISTA = "radiolista"; + public static String TYPE_CHECKLISTA = "checklista"; + public static String TYPE_ATTACH = "attach"; + public static String TYPE_ATTACH_POWT = "attach_powtarzalny"; + public static String TYPE_FOTO = "foto"; + public static String TYPE_SPECIAL = "special"; + public static String TYPE_TABELA = "tabela"; + public static String TYPE_RADIOBUTTON = "radiobutton"; + public static String TYPE_RADIO = "radio"; + + + // values for: STRUCT_KLIENT + // accept, tak, + + // values for: STRUCT_STATUS + // + + + public abstract OnClickListener getZapisz_zmiany( JSONObject jo, String typ); + protected abstract void setModified(); + protected abstract void stopAutozapis(); + protected abstract void mod_json_files(boolean mod_upload); + protected abstract void forceDoZapis(String key, String kod); + + // private static final int TAKE_PICTURE = 2; + SharedPreferences prefs; + JSONObject params = null; + JSONObject js =null; // json do wyświetlenia + String m_id = null; //nr zlecenia + ArrayList dluznikItems_names = null; + ArrayList dluznikItems_id_dluznik = null; + static Map selectedDluznikPerInterwencja = null; + + protected Class getDokumentyKollektoActivity() { + return DokumentyKollektoActivity.class; + } + + private class OnClickListenerInsertKp implements OnClickListener { + JSONArray kp_json_arr = null; + ArrayList items_id = null; + Spinner spin = null; + + public OnClickListenerInsertKp(JSONArray kp_json_arr, ArrayList items_id, Spinner spin) { + this.kp_json_arr = kp_json_arr; + this.items_id = items_id; + this.spin = spin; + } + + private int get_min_kp() { + int min_kp = -1; + + try { + for ( int i = 0 ; i < kp_json_arr.length() ; i++ ) { + JSONObject kp_json = kp_json_arr.getJSONObject(i); + if( !"aktywne".equals(kp_json.getString("status")) ) { continue; } + int kp = kp_json.getInt("kp"); + if( min_kp < 0 ) { + min_kp = kp; + } + else if( kp < min_kp ) { + min_kp = kp; + } + + } + } catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + } + + return min_kp; + } + + @Override + public void onClick(View v) { + int min_kp = get_min_kp(); + if( min_kp > 0 ) { + String old_kp_str = spin.getSelectedItem().toString(); + boolean setselection = true; + if ( IsInteger(old_kp_str) ) { + int old_kp = Integer.parseInt(old_kp_str); + if (min_kp >= old_kp) { + setselection = false; + } + } + if( setselection ) { + int pos_new = getPositionByValue(Integer.toString(min_kp), items_id); + if (pos_new >= 0) { + spin.setSelection(pos_new); + } + } + } + Log.d("my_debug", "min_kp: "+min_kp); + } + } + + protected class Opcje { + Map options = new HashMap(); + public Opcje( JSONObject jo){ + try { + if( jo.has(STRUCT_OPCJE)) { + String opcje = jo.getString(STRUCT_OPCJE); + //String tbl_opcje[] = opcje.split("|"); + StringTokenizer st = new StringTokenizer(opcje, "|"); + while(st.hasMoreTokens()){ + //for( int i=0; i< tbl_opcje.length; i++ ){ + //String tbl_p[] = tbl_opcje[i].split("="); + String tbl_p[] = st.nextToken().split("="); + if( tbl_p.length>1){ + options.put(tbl_p[0].trim().toLowerCase(), tbl_p[1].trim()); + }else{ + options.put(tbl_p[0].trim().toLowerCase(), ""); + } + } + } + } catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + } + } + public boolean check_opcje( String opcja){ + return options.keySet().contains(opcja.trim().toLowerCase()); + } + public String get_opcje(String opcja) { + return options.get(opcja.trim()); + } + } + + public class ShortButton { //extends Button{ + LinearLayout ll; + Button button; + public ShortButton(Context context) { + ll = new LinearLayout(context); + ll.setOrientation(LinearLayout.HORIZONTAL); + button = new Button(context); + ll.addView(button); + } + public LinearLayout getLinearLayout() { + return ll; + } + public Button getButton() { + return button; + } + } + + + protected static final int TAKE_PICTURE = 2; + public final String LOG = "MainActivity"; + + Map radioParentsIds = new HashMap(); // buttonId, ID grupy + Map> radiogroups = new HashMap>(); // ID grupy i lista buttonow + + Map radioJson = new HashMap(); //buttonId i dzieci do wyďż˝wietlenia + Map checkJson = new HashMap(); //buttonId i dzieci do wyďż˝wietlenia + Map groupContainer = new HashMap(); // ID grupy radio i Vidok do umieszczania dzieci. + + Map wyborSelected = new HashMap(); // ID pola wobor oraz id wybranego pola. + Map> items_id = new HashMap>(); // id pola wybor trzyma id dzieci pola wybďż˝r + + Integer maxId = 0; // maksymalne id z formatki (potrzebne do pďż˝l powtarzalnych) + Map> ostatni_powtarzalny = new HashMap>(); // id_wiersz_szablonu pola powtarzalnego oraz id_zlecenia_wiersz ostatniego pola (potrzebne aby wďż˝wietlaďż˝ tylko jeden button "Dodaj nowy") + Map> ostatni_accept = new HashMap>(); // id_wiersz_szablonu pola accept oraz id_zlecenia_wiersz ostatniego pola (potrzebne aby wďż˝wietlaďż˝ tylko jeden button "Dodaj nowy") + Map> ilosc_powtarzalnych = new HashMap>(); // id_wiersz_szablonu pola powtarzalnego oraz ile razy wystďż˝puje (potrzebne aby przycisk usuďż˝ nie mďż˝gďż˝ usuwaďż˝ ostatniego elementu) + Map> tabela_ostatni_wiersz = new HashMap>(); // id tabeli oraz id tych pĂłl ktĂłre stanowiÄ… ostatni wiersz danej tabeli + Map elemntsWithFoto = new HashMap(); // id elementu powtarzalnego ktďż˝ry zawiera element typu foto (potrzebne po to aby przy elemntach ktďż˝re zawierajďż˝ foto nie wyďż˝wietlaďż˝ "dodaj nowy" i "usuďż˝") + Map disableEditable = new HashMap(); // id pola ktĂłre mimo tego ĹĽe jest wyłączone (enable) jest do edycji (np. data) - potrzebne do walidacji + + Map elemntsEnable = new HashMap(); // id elementu -> czy jest enable (uzywane dla fragmentow) + + String komunikat_obowiazkowe = ""; //zmienna z komunikatem, jeĹ›li sÄ… pola sÄ… nie wypeĹ‚nione + String komunikat_walidacja = ""; //zmienna z komunikatem, jeĹ›li sÄ… pola Ĺşle wypeĹ‚nione + + boolean is_notend_intevention = false; + + Boolean bTablet=true; + Boolean first_foto_displayed = false; // zmienna trzymajďż˝ca czy byďż˝o juďż˝ wyďż˝wietlone pole typu foto. Potrzebne aby wyďż˝wietliďż˝ tylko raz "Zrďż˝b zdjďż˝cie" + + ArrayList folderIds = new ArrayList(); + ArrayList folderNazwy = new ArrayList(); + + Resources res; + protected int scrollTo = 0; + Map pola_tabela = new HashMap(); // płaska sktruktura zawierająca id => jsonobject z parametrami + + JSONObject supportOnLoadReferences = null; + + protected File saveToModFile(JSONObject jsToSave ) throws IOException { + DedalHelper.putFileContent(prefs.getString("dir", "") + "/baza/" + m_id + ".mod", jsToSave.toString()); + File dst = new File(prefs.getString("dir", "") + "/baza/" + m_id + ".mod"); + return dst; + } + + protected String saveToTMPFile() { + FileOutputStream fos; + File dst = null; + try { + dst = File.createTempFile("dedal", m_id); + DedalHelper.putFileContent(dst.getAbsolutePath(), js.toString()); + return dst.getAbsolutePath(); + } catch (IOException e) { + Log.e("DEDAL", "IO - saveToTMPFile", e); + } + return null; + } + + protected void wyswietlOpis(LinearLayout ll, JSONObject jo ) throws JSONException{ + TextView tw = new TextView(this); +// tw.setTextSize(18f); + tw.setTextAppearance(this, R.style.OpisText); + + + String opis = jo.getString(STRUCT_OPIS).trim(); + if( opis.length()>0) + tw.setMinimumWidth(300); + + //opis += " "; + +// if( opis.startsWith("<")){ + tw.setText(" " +Html.fromHtml(opis)); +// } + //tw.setText(jo.getString(STRUCT_TYP_DANYCH) + jo.getString("opcje") +": " + opis); +// tw.setText(opis); + // tw.setMaxWidth(600); + tw.setMaxWidth(1000); + if( opis.indexOf("=0){ + WebView webview = new WebView(this); + webview.loadData("" + opis + "", "text/html; charset=utf-8", "utf-8"); + ll.addView(webview); + }else{ + ll.addView(tw); + } + // + + + + } + File file = null; + int y = 0; + protected void wyswietlPole(LinearLayout ll, JSONObject jo) throws JSONException{ + + wyswietlPole(ll, jo, true, true); + } + + static final int DATE_DIALOG_ID = 999999; + static final int TIME_DIALOG_ID = 999998; + Date date_w; + int cur_Date_id = 0; + String cur_Date_opcje = ""; + GregorianCalendar c = new GregorianCalendar(); + + @Override + protected Dialog onCreateDialog(int id) { + switch (id) { + case DATE_DIALOG_ID: + // set date picker as current date + //Context ctx = getApplicationContext(); + if( date_w!=null){ + c.setTime(date_w); + } + DatePickerDialog dDlg = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { + + @Override + public void onDateSet(DatePicker view, int year, int monthOfYear, + int dayOfMonth) { + // TODO Auto-generated method stub + EditText et = (EditText) DedalActivity.this.findViewById(cur_Date_id); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); + GregorianCalendar c = new GregorianCalendar(); + c.set(Calendar.YEAR, year); + c.set(Calendar.MONTH, monthOfYear); + c.set(Calendar.DAY_OF_MONTH, dayOfMonth); + et.setText(sdf.format(c.getTime())); + setModified(); + if( !"only_date".equalsIgnoreCase(cur_Date_opcje)){ + showDialog(TIME_DIALOG_ID); + } + //cur_Date_opcje = ""; + } + }, c.get(Calendar.YEAR), c.get(Calendar.MONTH),c.get(Calendar.DAY_OF_MONTH)); + dDlg.getDatePicker().setCalendarViewShown(true); // - false -> true + dDlg.getDatePicker().setSpinnersShown(false); // - cała linijka + return dDlg; + case TIME_DIALOG_ID: + + TimePickerDialog tDlg = new TimePickerDialog(this, new OnTimeSetListener() { + + @Override + public void onTimeSet(TimePicker view, int hourOfDay, int minute) { + SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.ENGLISH); + EditText et = (EditText) DedalActivity.this.findViewById(cur_Date_id); + String prev = et.getText().toString(); + GregorianCalendar c = new GregorianCalendar(); + c.set(Calendar.HOUR_OF_DAY, hourOfDay); + c.set(Calendar.MINUTE, minute); + Log.d("my_debug", "set hour: "+hourOfDay); + if( prev.length()>=10){ + et.setText(prev.substring(0, 10) + " " +sdf.format(c.getTime())); + setModified(); + } + } + }, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true); + return tDlg; + } + + return null; + } + + protected int getMyAcceptId(JSONObject jo, String kod) { + + try { + if( kod != null && kod.equals(jo.getString("kod")) ){ + return jo.getInt("id"); + }else{ + //if( isset( $pole['parent'] ) && trim($pole['parent']) != '' && intval($pole['parent']) > 0 ){ + //Log.d("my_debug", "getMyAcceptId, jo: "+jo+", parent:"+jo.getString("parent") ); + String parent = jo.getString("parent"); + + + if( jo.has("parent") && jo.getInt("parent") > 0 && pola_tabela.containsKey(jo.getString("parent")) ) { + //Log.d("my_debug", "getMyAcceptId, wchodze w if, kod: "+kod); + return getMyAcceptId(pola_tabela.get(jo.getString("parent")), kod); + }else{ + //return -1; + return jo.getInt("id"); // root element + } + } + } catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + return -1; + } + } + + protected int getMyAcceptId(JSONObject jo, String kod, String value) { + + try { + if( kod.equals(jo.getString("kod")) && value.equals(jo.getString("wartosc"))){ + return jo.getInt("id"); + }else{ + //if( isset( $pole['parent'] ) && trim($pole['parent']) != '' && intval($pole['parent']) > 0 ){ + if( jo.has("parent") && jo.getInt("parent") > 0 && pola_tabela.containsKey(jo.getString("parent")) ) { + return getMyAcceptId(pola_tabela.get(jo.getString("parent")), kod, value); + }else{ + return -1; + } + } + } catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + return -1; + } + } + + protected int wyszukajNajmniejszy(String kod, String value) { + + Iterator it = pola_tabela.entrySet().iterator(); + int min = 0; + while (it.hasNext()) { + Map.Entry pair = (Map.Entry)it.next(); + String id = (String)pair.getKey(); + Integer id_int = Integer.parseInt(id); + JSONObject pole = (JSONObject)pair.getValue(); + try { + if( kod.equals(pole.getString("kod")) && value.equals(pole.getString("wartosc"))){ + if( min == 0 ) { + min = id_int; + } + else if( min > id_int ) { + min = id_int; + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + + it.remove(); // avoids a ConcurrentModificationException + } + return min; + +// $min = 0; +// foreach( $pola_tabela as $pole){ +// if( $pole['kod'] == $kod && $pole['wartosc'] == $value){// && $pole['id']!= $omitId) { +// if( $min == 0){ +// $min = $pole['id']; +// }else if( $min > $pole['id'] ){ +// $min = $pole['id']; +// } +// } +// } +// return $min; + + } + + protected String pobierzValue(JSONObject jo, String value) { + + try { + if( jo.has("typ_danych") && "radiolista".equals(jo.getString("typ_danych")) ) { + JSONObject find = find_element_from_Array(js, "kod", value); + if( find != null && find.has("id_wiersz_szablonu") ) { + value = find.getString("id_wiersz_szablonu"); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + + + return value; + } + + + protected void create_pole_tabela_recursive (JSONObject jo) { + //Map pole_tabela_fragment = new HashMap(); + try { + if( !jo.has("id") ) { + //Log.d("my_debug", "jo bez id: "+jo); + return; + } + String id = jo.getString("id"); + +// JSONObject jo_clone = new JSONObject(jo.toString()); +// if( jo_clone.has(STRUCT_CHILDS) ) { +// jo_clone.remove(STRUCT_CHILDS); +// } + pola_tabela.put(id, jo); + + if( jo.has(STRUCT_CHILDS) && jo.getJSONArray(STRUCT_CHILDS).length() > 0 ) { + JSONArray childsJ = jo.getJSONArray(STRUCT_CHILDS); + for( int i = 0 ; i < childsJ.length() ; i++ ) { + //JSONObject childJ = childsJ.getJSONObject(i); + create_pole_tabela_recursive(childsJ.getJSONObject(i)); + //pola_tabela.putAll(pole_tabela_fragment2); + } + } + else { + + } + + //return pola_tabela; + } catch (JSONException e) { + e.printStackTrace(); + } + + //return pola_tabela; + } + + protected void create_pole_tabela(JSONObject js) { + if( pola_tabela != null && pola_tabela.size() > 0 ) { + return; + } + + pola_tabela = new HashMap(); + + try { + JSONObject pola = js.getJSONObject("pola"); + Iterator k = pola.keys(); + JSONObject jo = null; + while (k.hasNext()) { + String key = (String) k.next(); + jo = pola.getJSONObject(key); + create_pole_tabela_recursive(jo); + //pola_tabela.putAll(pole_tabela_fragment); + } + } catch (JSONException e) { + e.printStackTrace(); + } + + } + + + protected boolean wyszukajCzyPierwszy(JSONObject jo, String kod, String value) { + + create_pole_tabela(js); +// Log.d("my_debug", "wyszukajCzyPierwszy, pola_tabela size: "+pola_tabela.size()); +// +// Log.d("my_debug", "test contains: "+pola_tabela.containsKey("90731296")); +// Iterator it = pola_tabela.entrySet().iterator(); +// while (it.hasNext()) { +// Map.Entry pair = (Map.Entry) it.next(); +// String id = (String) pair.getKey(); +// if( "90731296".equals(id) ) { +// Log.d("my_debug", "znalezione test, id: " + id); +// } +// } + + Log.d("my_debug", "value przed: "+value); + + value = pobierzValue(jo, value); + try { + Log.d("my_debug", "wyszukajCzyPierwszy, id: "+jo.getString("id")+", kod: "+kod+", value: "+value); + } catch (JSONException e) { + e.printStackTrace(); + } + + int m = getMyAcceptId(jo, kod, value); + int min = wyszukajNajmniejszy(kod, value); +// +// Log.d("my_debug", "m: "+m+", min: "+min+", value: "+value); +// return false; + return m == min || min == 0; + } + + + + protected void wyswietlPole(LinearLayout ll, JSONObject jo, Boolean withOpis, Boolean enable ) throws JSONException{ + wyswietlPole(ll, jo, withOpis, enable, null); + } + + //String status_interwencji = null; + + protected void wyswietlPole(LinearLayout ll, JSONObject jo, Boolean withOpis, Boolean enable, String status_interwencji ) throws JSONException{ + String typ_danych = jo.getString(STRUCT_TYP_DANYCH); + +// Log.d("my_debug", "pole, typ: "+typ_danych+", wartosc: "+jo.getString(STRUCT_WARTOST)+", opis: "+jo.getString(STRUCT_OPIS)+", id: "+jo.getInt("id") ); +// if( js.has("sub") && jo.has("id-orig") ) { +// Log.d("my_debug", "no-sent"); +// jo.put("no-sent", "true"); +// enable = false; +// } + + // sprawdzanie opcji 'if' + Opcje op = new Opcje(jo); + // todo: więszka optymalizacja bo działa wolno + + if( op.check_opcje("if") ) { + String opcjaIf = op.get_opcje("if"); + String split[] = opcjaIf.split(":"); + if( split.length > 1 ) { + String kod = split[0]; + String wartosc = split[1]; + boolean count = wyszukajCzyPierwszy( jo, kod, wartosc ); + + if( count ){ + // echo "Znaleziono kod $opcjaIf pierwszy."; + //echo '
'; + return; + } + } + + } + + // koniec sprawdzanie opcji 'if' + + String dane_we = jo.getString(STRUCT_KLIENT); + if ( "accept".equals(dane_we) ) { + status_interwencji = jo.getString(STRUCT_STATUS); + //if( jo.getString(STRUCT_STATUS).equals("end") + } + + // wyłom - dla niektórych szablonów pola wyjściowe mają być edytowalne dla statusu wykonane + if( js.has("edycja_pol_wyjsciowych") ) { + JSONArray edycja_pol_wyjsciowych = js.getJSONArray("edycja_pol_wyjsciowych"); + String status_zlecenia = params.getString(STRUCT_STATUS); + + if( "nie".equals(dane_we) || "accept".equals(dane_we) ) { // dane wyjściowe + + + for (int i = 0; i < edycja_pol_wyjsciowych.length(); i++) { + JSONObject warunek = edycja_pol_wyjsciowych.getJSONObject(i); + if (status_zlecenia.equals(warunek.get("status_zlecenia")) + && "INS".equals(warunek.get("user_typ"))) { + + if( status_interwencji == null || (!"end".equals(status_interwencji) && !"accept".equals(status_interwencji)) ) { + enable = true; + } + } + } + } + } + /// + + if(jo.has("no-sent")) { + enable = false; + } + + int id = 0; + if( jo.has("id") ) { + id = jo.getInt("id"); + } + else { + return; + } + + if ( jo.has("usun") && jo.getString("usun").equals("true") ) { + return; + } + + if ( id > maxId ) { + maxId = jo.getInt("id"); + } + + //Log.d("my_debug", "przed powtarzalny, id: "+jo.getInt("id")); + //Log.d("my_debug", "przed pow: "+typ_danych +", id: "+jo.getString("id")); + if(jo.getString(STRUCT_POWTARZALNY).equals("tak") && + !jo.getString(STRUCT_KLIENT).equals("accept") && + elemntsWithFoto.get(jo.getInt("id")) == null && + enable) { + //Log.d("my_debug", "w powtarzalny "+typ_danych +", id: "+jo.getString("id")); + } + + //return; + if(typ_danych.equals(TYPE_CHECK)) { + wyswietl_checkbox(ll, jo, withOpis, enable, status_interwencji); + } + else { + if (typ_danych.equals(TYPE_DATA)) { +// if( withOpis) wyswietlOpis(ll, jo); + wyswietl_date(ll, jo, withOpis, enable); + wyswietl_Dzieci(ll, jo, withOpis, enable, status_interwencji); + + } else if (typ_danych.equals(TYPE_TEXT) || typ_danych.equals(TYPE_KOLUMNA) || + typ_danych.equals(TYPE_TEXTBOX) || typ_danych.equals(TYPE_LICZBA) || + typ_danych.equals(TYPE_KWOTA)) { + + wyswietl_text(ll, jo, withOpis, enable, typ_danych); + wyswietl_Dzieci(ll, jo, withOpis, enable, status_interwencji); + + } else if (typ_danych.equals(TYPE_WYBOR)) { + wyswietl_wybor(ll, jo, withOpis, enable); + + } else if (typ_danych.equals(TYPE_RADIOLISTA)) { + wyswietl_radiolista(ll, jo, withOpis, enable, status_interwencji); + + } else if (typ_danych.equals(TYPE_LISTA) || typ_danych.equals(TYPE_CHECKLISTA)) { + enable = wyswietl_liste(ll, jo, withOpis, enable, status_interwencji); + + } else if (typ_danych.equals(TYPE_ATTACH)) { + wyswietl_attach(ll, jo, "", enable); + wyswietl_Dzieci(ll, jo, withOpis, enable, status_interwencji); + + } else if (typ_danych.equals(TYPE_ATTACH_POWT)) { + wyswietl_attach(ll, jo, STRUCT_POWTARZALNY, enable); + wyswietl_Dzieci(ll, jo, withOpis, enable, status_interwencji); + } else if (typ_danych.equals(TYPE_FOTO)) { + //Log.d("my_debug", "wyswietl_foto 1"); + wyswietl_foto(ll, jo, enable); + wyswietl_Dzieci(ll, jo, withOpis, enable, status_interwencji); + + } else if (typ_danych.equals(TYPE_SPECIAL)) { + //Log.d("my_debug", "ojoj special"); + wyswietl_special(ll, jo, withOpis, enable); + //return; + } else if (typ_danych.equals(TYPE_TABELA)) { + wyswietl_tabela(ll, jo, withOpis, enable); + //return; + } else { + // nie powinno się zdarzać + Log.e("myDebug", "wyswietlanie nieznanego elementu: "+typ_danych); + TextView tw2 = new TextView(this); + tw2.setText("typ: " + typ_danych); + ll.addView(tw2); + + wyswietlOpis(ll, jo); + wyswietl_Dzieci(ll, jo, withOpis, enable, status_interwencji); + } + } + + if(jo.getString(STRUCT_POWTARZALNY).equals("tak") && + !jo.getString(STRUCT_KLIENT).equals("accept") && + elemntsWithFoto.get(jo.getInt("id")) == null && + enable ) { + + //Log.d("my_debug", "sub: "+) + if( !(js.has("sub") && jo.has("id-orig")) ) { + ShortButton b2 = new ShortButton(this); + b2.getButton().setText( res.getString(R.string.usun) ); + OnClickListener nClickL_usun = new Usun_powtarzalny(jo); + b2.getButton().setOnClickListener(nClickL_usun); + ll.addView(b2.getLinearLayout()); + } + + //Log.d("my_debug", "w powtarzalny"); + ShortButton b = null; + LinearLayout ll_pow = null; + Integer x = ostatni_powtarzalny.get(jo.getInt("parent")).get(jo.getInt("id_wiersz_szablonu")); + if( !jo.has("id-orig") && x != null && jo.getInt("id") == x) { + b = new ShortButton(this); + b.getButton().setText("Dodaj nowy"); + //b.setId(jo.getInt("id")); + ll_pow = new LinearLayout(this); + ll_pow.setOrientation(LinearLayout.VERTICAL); + OnClickListener nClickL = new Dodaj_powtarzalny(ll_pow, jo); + b.getButton().setOnClickListener(nClickL); + + ll.addView(ll_pow); + ll.addView(b.getLinearLayout()); + + } + } + + } + + private void wyswietl_text(LinearLayout ll, JSONObject jo, Boolean withOpis, Boolean enable, String typ_danych) throws JSONException { + if (jo.getString(STRUCT_KLIENT).equals("tak") || !enable) { + //cb.setClickable(false); +// et.setText(jo.getString(STRUCT_WARTOST)); +// wyswietl_text_ramka(ll, Html.fromHtml(jo.getString(STRUCT_WARTOST))); + LinearLayout llv = ll; + if (withOpis) { + if (!typ_danych.equals(TYPE_TEXTBOX)) { + llv = new LinearLayout(this); + + llv.setOrientation(LinearLayout.HORIZONTAL); + ll.addView(llv); + } + wyswietlOpis(llv, jo); + } + // String typ_danych = jo.getString(STRUCT_TYP_DANYCH); + if( typ_danych.equals(TYPE_TEXTBOX)){ + String t = jo.getString(STRUCT_WARTOSC); + // t = t.replace("
", "/n"); + // Spanned text= Html.fromHtml(t); + // wyswietl_text_ramka_dopasowana(llv, text); + TextView two = new TextView(this); ///BorderTextView(this); + // two.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT)); + two.setBackgroundColor(Color.YELLOW); + two.setText(t);//ext); + two.setMinWidth(100); + two.setMaxWidth(600); + llv.addView(two); + + // wyswietl_text_ramka_dopasowana(llv, jo.getString(STRUCT_WARTOSC)); + }else { + if( withOpis) + wyswietl_text_ramka(llv, jo.getString(STRUCT_WARTOSC)); + else + wyswietl_text_ramka_dopasowana(llv, jo.getString(STRUCT_WARTOSC)); + } + + } else { + wyswietl_editText(ll, jo, withOpis, enable); + + } + } + + private void wyswietl_date(LinearLayout ll, JSONObject jo, Boolean withOpis, Boolean enable) throws JSONException { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); + date_w = null; + try { + date_w = sdf.parse(jo.getString(STRUCT_WARTOSC)); + } catch (ParseException e) { + //e.printStackTrace(); + } + + if (!jo.getString(STRUCT_KLIENT).equals("tak") && enable) { + wyswietl_editDate(ll, jo, withOpis, enable); + } else { + // read only + LinearLayout llv = ll; + if (withOpis) { + llv = new LinearLayout(this); + llv.setOrientation(LinearLayout.HORIZONTAL); + ll.addView(llv); + wyswietlOpis(llv, jo); + } + wyswietl_text_ramka(llv, jo.getString(STRUCT_WARTOSC)); + } + } + + private void wyswietl_wybor(LinearLayout ll, JSONObject jo, Boolean withOpis, Boolean enable) throws JSONException { + if (withOpis) wyswietlOpis(ll, jo); + ArrayList items = new ArrayList(); + JSONArray ja = jo.getJSONArray(STRUCT_CHILDS); + //items_id.removeAll(items_id); + ArrayList items_id_temp = new ArrayList(); + if (jo.has("obowiazkowe") && "tak".equals(jo.getString("obowiazkowe"))) { + items.add(" "); + items_id_temp.add(0); + } + + Spinner spin = new Spinner(DedalActivity.this); //(Spinner) findViewById(R.id.spinner); + + boolean do_default = true; + Button wstaw_automatycznie_btn = new Button(this); + if (true) { + // boolean czy_formatka_ma_dluznikow + + + if( selectedDluznikPerInterwencja != null ) { + if (jo.has("opcje") && jo.has("id_interwencji") && ("adresy".equals(jo.getString("opcje")) || "telefony".equals(jo.getString("opcje")) ) ) { + String id_interwencji = jo.getString("id_interwencji"); + String id_dluznika = selectedDluznikPerInterwencja.get(id_interwencji); + if( id_dluznika != null ) { + JSONArray jdluznicy = js.getJSONArray("dluznicy"); + JSONObject jdluznik = null; + // znajdz odpowiedniego dluznika + for( int i = 0 ; i < jdluznicy.length() ; i++ ) { + JSONObject jdluznik_temp = jdluznicy.getJSONObject(i); + if( jdluznik_temp.has("id") && id_dluznika.equals(jdluznik_temp.getString("id")) ) { + jdluznik = jdluznik_temp; + break; + } + } + if( "adresy".equals(jo.getString("opcje")) && jdluznik != null && jdluznik.has("adresy") ) { + JSONArray jAdresy = jdluznik.getJSONArray("adresy"); + for ( int i = 0 ; i < jAdresy.length() ; i++ ) { + JSONObject jAdres = jAdresy.getJSONObject(i); + if( jAdres.has("kod_pocztowy") && jAdres.has("miejscowosc") && jAdres.has("ulica") && jAdres.has("nr_domu") ) { + items.add(jAdres.getString("kod_pocztowy") + " " + jAdres.getString("miejscowosc") + " " + jAdres.getString("ulica") + " " + jAdres.getString("nr_domu")); + items_id_temp.add(i); + } + } + + do_default = false; + } + if( "telefony".equals(jo.getString("opcje")) && jdluznik != null && jdluznik.has("telefony") ) { + JSONArray jTelefony = jdluznik.getJSONArray("telefony"); + for ( int i = 0 ; i < jTelefony.length() ; i++ ) { + JSONObject jTelefon = jTelefony.getJSONObject(i); + if( jTelefon.has("telefon") && jTelefon.has("typ_telefonu") && jTelefon.has("opis_telefonu") && jTelefon.has("czy_zweryfikowany") ) { + items.add(jTelefon.getString("telefon") + " " + jTelefon.getString("typ_telefonu") + " " + jTelefon.getString("opis_telefonu") + " " + jTelefon.getString("czy_zweryfikowany")); + items_id_temp.add(i); + } + } + + do_default = false; + } + } + } else if (jo.has("opcje") && "telefony".equals(jo.getString("opcje"))) { + // todo: zrobić telefony analogicznie jak adresy + do_default = false; + } + } + + if (jo.has("opcje") && "kp_numer".equals(jo.getString("opcje"))) { + if( enable) { + String KP_filename = prefs.getString("KP_filename", ""); + KP_filename = DedalHelper.getModOrJsonFileName(KP_filename); + String kp_json_str = DedalHelper.getFileContent(KP_filename); + JSONArray kp_json_arr = new JSONArray(kp_json_str); + for (int i = 0; i < kp_json_arr.length(); i++) { + JSONObject kp_json = kp_json_arr.getJSONObject(i); + String status = kp_json.getString("status"); + if (!"aktywne".equals(status)) { + continue; + } + + items.add(kp_json.getString("kp")); + items_id_temp.add(kp_json.getInt("kp")); + } + + wstaw_automatycznie_btn.setText("Wstaw automatycznie"); + wstaw_automatycznie_btn.setOnClickListener(new OnClickListenerInsertKp(kp_json_arr, items_id_temp, spin)); + }else{ + items.clear(); + items.add(jo.getString("wartosc")); + //items_id_temp.add(0); + } + do_default = false; + } + + } + + if( ja != null && ja.length() > 0 && do_default ) { + for (int i = 0; i < ja.length(); i++) { + items.add(ja.getJSONObject(i).getString(STRUCT_OPIS)); + items_id_temp.add(ja.getJSONObject(i).getInt("id_wiersz_szablonu")); + } + } + items_id.put(jo.getInt("id"), items_id_temp); + + + spin.setId(jo.getInt("id")); + if (!enable) { + spin.setEnabled(false); + } + //Log.d("my_debug", "spinner Id:"+spin.getId()); + //Log.d("my_debug", "items: "+items_id); + ArrayAdapter aa = new ArrayAdapter( + this, + android.R.layout.simple_spinner_item, + items.toArray()); + + aa.setDropDownViewResource( + android.R.layout.simple_spinner_dropdown_item); + + spin.setOnItemSelectedListener(new OnItemSelectedListener() { + boolean first_selection = true; + + @Override + public void onItemSelected(AdapterView parent, View view, int pos, long id) { + ArrayList items_id_temp = items_id.get(parent.getId()); + wyborSelected.put(parent.getId(), items_id_temp.get(pos)); + Log.d("my_debug", "spinner, id: " + parent.getId() + ", selected: " + items_id_temp.get(pos)); + if( !first_selection ) { + setModified(); + } + else { + first_selection = false; + } + } + + @Override + public void onNothingSelected(AdapterView arg0) { + } + }); + + spin.setAdapter(aa); + + int selected_pos = 0; + if (jo.has(STRUCT_WARTOSC) && !jo.getString(STRUCT_WARTOSC).equals("") && !jo.getString(STRUCT_WARTOSC).equals("obowiazkowe")) { + selected_pos = getPositionByValue(jo.getString(STRUCT_WARTOSC), items_id_temp); + + } + Log.d("my_debug", "selected-pos:" + selected_pos); + spin.setSelection(selected_pos); + + ll.addView(spin); + + //przycisk: "wstaw automatycznie" + if (jo.has("opcje") && "kp_numer".equals(jo.getString("opcje"))) { + ll.addView(wstaw_automatycznie_btn); + } + } + + private int getPositionByValue(String value, ArrayList items_id_temp) { + int selected_pos = 0; + //String wartosc = jo.getString(STRUCT_WARTOSC); + Log.d("my_debug", "wartosc: " + value); + if( IsInteger(value) ) { + int wartosc_int = Integer.parseInt(value); //jo.getInt(STRUCT_WARTOSC); + for (int i = 0; i < items_id_temp.size(); i++) { + //Log.d("my_debug", i+ ", (Integer)wartosc: "+(Integer)wartosc+", "+items_id_temp.get(i)); + if ( wartosc_int == items_id_temp.get(i)){ + selected_pos = i; + break; + } + } + } + return selected_pos; + } + + private Boolean wyswietl_liste(LinearLayout ll, JSONObject jo, Boolean withOpis, Boolean enable) throws JSONException { + return wyswietl_liste(ll, jo, withOpis, enable, null); + } + + private Boolean wyswietl_liste(LinearLayout ll, JSONObject jo, Boolean withOpis, Boolean enable, final String status_interwencji) throws JSONException { + /**/ + LinearLayout ll_wrapper = new LinearLayout(DedalActivity.this); + ll_wrapper.setOrientation(LinearLayout.VERTICAL); + ll.addView(ll_wrapper); + /* i dalej pozmieniane ll na ll_wraper w tej funkcji*/ + ll=ll_wrapper; + if (withOpis) wyswietlOpis(ll, jo); /* llv na ll*/ + + Opcje op = new Opcje(jo); + LinearLayout llv = new LinearLayout(this); + ll.addView(llv); + + if (op.check_opcje("col") && bTablet || op.check_opcje("fragment")) { + llv.setOrientation(LinearLayout.HORIZONTAL); + } else { + llv.setOrientation(LinearLayout.VERTICAL); + llv.setMinimumWidth(this.getWindow().getAttributes().width); + } + + try { + String dane_we = jo.getString(STRUCT_KLIENT); + if (dane_we.equals("accept")) { + + if (jo.getString(STRUCT_STATUS).equals("end")) { + enable = false; //Log.d("my_debug", "enable: "+enable); + } else if (jo.getString(STRUCT_STATUS).equals("accept")) { + enable = false; + } + + //todo: wybór dłużnika w interwencji + /////////////////////////////////////////// + if( js.has("dluznicy") && dluznikItems_names != null && dluznikItems_names.size() > 0) { + JSONArray jdluznicy = js.getJSONArray("dluznicy"); + //ArrayList dluznikItems_names = new ArrayList(); + + Spinner dluznikSpinner = new Spinner(DedalActivity.this); //(Spinner) findViewById(R.id.spinner); + //dluznikSpinner.setId(jo.getInt("id")); + if (!enable) { + dluznikSpinner.setEnabled(false); + } + + ArrayAdapter aa = new ArrayAdapter( + this, + android.R.layout.simple_spinner_item, + dluznikItems_names.toArray()); + + aa.setDropDownViewResource( + android.R.layout.simple_spinner_dropdown_item); + + + selectedDluznikPerInterwencja = null; + dluznikSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener(jo.getString("id"))); + dluznikSpinner.setAdapter(aa); + + if( jo.has("id_dluznika") ) { + String selected_id_dluznika = jo.getString("id_dluznika"); + + int selected_pos = 0; + for (int i = 0; i < dluznikItems_id_dluznik.size(); i++) { + String id_dluznika = dluznikItems_id_dluznik.get(i); + if( selected_id_dluznika.equals(id_dluznika) ) { + selected_pos = i; + break; + } + } + Log.d("my_debug", "selected-pos:" + selected_pos); + dluznikSpinner.setSelection(selected_pos); + } + + TextView dluznikOpisTv = new TextView(this); + dluznikOpisTv.setText("Dłużnik: "); + + LinearLayout dluznikLL = new LinearLayout(this); + dluznikLL.addView(dluznikOpisTv); + dluznikLL.addView(dluznikSpinner); + llv.addView(dluznikLL); + } + //////////////////////////////////////////// + } + + if (jo.getString(STRUCT_KLIENT).equals("tak") || !enable) { + llv.setBackgroundColor(Color.parseColor("#eaeaea"));//#eaeaea //B0E0E6 + } else { + //llv.setBackgroundColor(Color.WHITE); + } + boolean schowaj = false; + if( op.check_opcje("hide_ended")&& !enable){ + schowaj = true; + } + if (op.check_opcje("fragment") || schowaj ){ + // LOG + Log.d("my_debug", "obsluga fragmentu"); + Button bu_t = new Button(this); + bu_t.setId(jo.getInt("id")); + bu_t.setText( "Pokaż w nowym oknie +" ); + elemntsEnable.put(jo.getInt("id"), enable); + + Log.d("my_debug", "wyswietl_liste: "+jo.getString("kod")+", enable: "+enable.toString()); + + OnClickListener nClickL_t = new OnClickListener() { + //public String s; + @Override + public void onClick(View v) { + stopAutozapis(); + + scrollTo = sw.getScrollY();//sw.getFirstVisiblePosition(); + Log.d("my_debug", "set scrollTo: "+scrollTo); + + Intent i = new Intent(DedalActivity.this, FragmentMainActivity.class); + // i.putExtra("json", js.toString()); + String filePathName = saveToTMPFile(); + i.putExtra("filePathName", filePathName); + i.putExtra("id", "" + v.getId()); + i.putExtra("enable", "" + elemntsEnable.get(v.getId())); + if( status_interwencji != null ) { + i.putExtra("status_interwencji", status_interwencji); + } + startActivityForResult(i, REQUEST_CODE); + //startActivity(i); + + }}; + bu_t.setOnClickListener(nClickL_t); + llv.addView(bu_t); + }else { + llv.setId(jo.getInt("id")); //tu chyba nie jest potrzebne + JSONArray ja = jo.getJSONArray(STRUCT_CHILDS); + if (ja != null && ja.length() > 0) { + for (int i = 0; i < ja.length(); i++) { + LinearLayout llh = new LinearLayout(this); + llh.setOrientation(LinearLayout.VERTICAL); + if( ! op.check_opcje("col")) { // dla list kolumnowych nie dawaj odstępu z lewej + llh.setPadding(20, 0, 0, 0); + } + //llh.setBackgroundColor(Color.WHITE); + llv.addView(llh); + wyswietlPole(llh, ja.getJSONObject(i), withOpis, enable, status_interwencji); + } + if (ja.length() > 6) { + llv.setMinimumHeight(ja.length() * 55); + } + } + } + + if (dane_we.equals("accept")) { +// llv.setBackgroundColor(Color.WHITE); + if (enable) { + llv.setBackgroundColor(Color.parseColor("#FAFAD2")); + } + + if (jo.getString(STRUCT_STATUS).equals("notend")) { + if (enable) { + ShortButton b = new ShortButton(this); + b.getButton().setText(res.getString(R.string.zakoncz_wizyte)); //res.getString(R.string.zakoncz_wizyte) ); + OnClickListener nClickL_zakoncz = getZapisz_zmiany(jo, "zakoncz_wizyte"); + b.getButton().setOnClickListener(nClickL_zakoncz); + ll.addView(b.getLinearLayout()); + } + } else if (jo.getString(STRUCT_STATUS).equals("end")) { + TextView tw = new TextView(this); + tw.setText(res.getString(R.string.zakonczone)); + tw.setTextColor(Color.RED); + ll.addView(tw); + + } else if (jo.getString(STRUCT_STATUS).equals("accept")) { + TextView tw = new TextView(this); + tw.setText(res.getString(R.string.zaakceptowane)); + tw.setTextColor(Color.GREEN); + ll.addView(tw); + + } + + // wyĹ›wietlanie przycisku dodaj wizytÄ™ + if ((jo.getString(STRUCT_STATUS).equals("accept") || jo.getString(STRUCT_STATUS).equals("end")) + && ostatni_accept.get(jo.getInt("parent")) != null && ostatni_accept.get(jo.getInt("parent")).get(jo.getInt("id_wiersz_szablonu")) != null + && ostatni_accept.get(jo.getInt("parent")).get(jo.getInt("id_wiersz_szablonu")) == jo.getInt("id")) { + +// if (params.getString(STRUCT_STATUS).equals("przydz_odeb") && !jo.has("dodawanie_wizyty")) { +// ShortButton b = new ShortButton(this); +// b.getButton().setText(res.getString(R.string.dodaj_wizyte)); +// OnClickListener nClickL_zakoncz = getZapisz_zmiany(jo, "dodaj_wizyte"); +// b.getButton().setOnClickListener(nClickL_zakoncz); +// ll.addView(b.getLinearLayout()); +// } + if (jo.has("dodawanie_wizyty")) { + TextView tw = new TextView(this); + tw.setText(res.getString(R.string.trwa_dodawanie_wizyty)); + tw.setTextColor(Color.YELLOW); + ll.addView(tw); + + ButtonDate b = new ButtonDate(this); + //b.setEdId(et.getId()); + b.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + DedalActivity.this.reload(); + } + }); + b.setText(res.getString(R.string.odswiez_widok_zlecenia_z_serwera)); + ll.addView(b); + + } + } + } + } catch (JSONException jE) { + + } + return enable; + } + + private void wyswietl_Dzieci(LinearLayout ll, JSONObject jo, Boolean withOpis, Boolean enable) throws JSONException { + wyswietl_Dzieci(ll, jo, withOpis, enable, null); + } + + private void wyswietl_Dzieci(LinearLayout ll, JSONObject jo, Boolean withOpis, Boolean enable, String status_interwencji) throws JSONException { + JSONArray ja = jo.getJSONArray(STRUCT_CHILDS); + if (ja != null && ja.length() > 0) { + for (int i = 0; i < ja.length(); i++) { + wyswietlPole(ll, ja.getJSONObject(i), withOpis, enable, status_interwencji); + } + } + } + + protected void wyswietl_editDate(LinearLayout ll, JSONObject jo, + Boolean withOpis, Boolean enable) throws JSONException { + + EditText et = new EditText(this); + et.setBackgroundColor(Color.WHITE); + et.setEnabled(false); //read only + + + //et.setText(jo.getString(STRUCT_WARTOSC)); + // wartość albo wartość domyślna + String wartosc = jo.getString(STRUCT_WARTOSC); + //Log.d("my_debug", "data") + if( enable && wartosc.trim().equals("") ) { + Opcje op = new Opcje(jo); + if( op.check_opcje("default_for_tablet") ) { + String default_value = op.get_opcje("default_for_tablet"); + wartosc = default_value; + if( "PRE_TODAY".equals(default_value) ) { + wartosc = DedalHelper.getCurrentDate("yyyy-MM-dd HH:mm"); + } + } + } + et.setText(wartosc); + + et.setId(jo.getInt("id")); + + + LinearLayout llv = ll; + llv = new LinearLayout(this); + llv.setOrientation(LinearLayout.HORIZONTAL); + ll.addView(llv); + + if( withOpis) { + wyswietlOpis(llv, jo); + } + + llv.addView(et); + + if( !jo.getString(STRUCT_KLIENT).equals("tak") && enable){ + ButtonDate b = new ButtonDate(this); + b.setEdId(et.getId()); + b.setOnClickListener(new Ustaw_date(jo.getString(STRUCT_OPCJE))); + + b.setText( res.getString(R.string.zmien_date) ); + llv.addView(b); + Opcje op = new Opcje(jo); + //if( !"only_date".equalsIgnoreCase(jo.getString(STRUCT_OPCJE))){ + if( !op.check_opcje("only_date")){ + b = new ButtonDate(this); + b.setEdId(et.getId()); + b.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + cur_Date_id = ((ButtonDate)v).getEdId(); + showDialog(TIME_DIALOG_ID); + } + }); + b.setText( "ustaw czas");// res.getString(R.string.zmien_date) ); + llv.addView(b); + } + + disableEditable.put(jo.getInt("id"), true); + } + } + + protected void wyswietl_editText(LinearLayout ll, JSONObject jo, + Boolean withOpis, Boolean enable) throws JSONException { + String typ_danych = jo.getString(STRUCT_TYP_DANYCH); + int id = 0; + if( jo.has("id") ) { + id = jo.getInt("id"); + } + EditText et = new EditText(DedalActivity.this); + + String wartosc = jo.getString(STRUCT_WARTOSC); + if( enable && wartosc.trim().equals("") ) { + Opcje op = new Opcje(jo); + if( op.check_opcje("default_for_tablet") ) { + String default_value = op.get_opcje("default_for_tablet"); + wartosc = default_value; + if( "PRE_TODAY".equals(default_value) ) { + wartosc = DedalHelper.getCurrentDate("yyyy-MM-dd HH:mm"); + } + } + } + et.setText(wartosc); + + if( jo.getString(STRUCT_KLIENT).equals("tak") || !enable){ + //tutaj nie wejdzie... + et.setEnabled(false); + + }else{ + et.setMinWidth(120); + } + + + + LinearLayout llv = ll; + if( withOpis) { + if( !typ_danych.equals(TYPE_TEXTBOX)){ + llv = new LinearLayout(this); + llv.setOrientation(LinearLayout.HORIZONTAL); + ll.addView(llv); + } + wyswietlOpis(llv, jo); + } + + if( typ_danych.equals(TYPE_TEXTBOX)){ + et.setMinLines(4); + } + llv.addView(et); + + et.setId(jo.getInt("id")); + if(typ_danych.equals(TYPE_LICZBA)) + et.setInputType(InputType.TYPE_CLASS_NUMBER ); + + et.addTextChangedListener(new TextWatcher() { + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + } + + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + @Override + public void afterTextChanged(Editable s) { + setModified(); + //Log.d("my_debug", "after TEXT CHANGED"); + } + }); + String walidacja = jo.getString(STRUCT_WALIDACJA).trim(); + // walidacja formatu wpisanych danych + if ( ( jo.has(STRUCT_WALIDACJA) && ( walidacja.equals("kod_pocztowy") || walidacja.equals("telefon") )) + || typ_danych.equals(TYPE_KWOTA) || typ_danych.equals(TYPE_LICZBA) || ( typ_danych.equals(TYPE_LICZBA) && walidacja.equals(".") && walidacja.equals(",") ) ) { + //Log.d("my_debug", "1walid poprawnosci, id" + id); + //if( !et.getText().toString().trim().equals("") && ( et.isEnabled() || disableEditable.get(id) != null ) ) { + if( et.isEnabled() || disableEditable.get(id) != null ) { + //Log.d("my_debug", "2walid poprawnosci, id" + id); + et.setOnFocusChangeListener(new Walidacja_poprawnosci(jo.getString(STRUCT_WALIDACJA).trim(), typ_danych)); + //et.setOnFocusChangeListener(null); + } + } + + + + } + + protected JSONObject find_element_from_Array(JSONObject js, String id){ + return find_element_from_Array(js, "id", id); + } + + protected JSONObject find_element_from_Array(JSONObject js, String seek_key, String seek_value){ + JSONObject pola = null; + JSONObject ret = null; + try { + pola = js.getJSONObject("pola"); + Iterator k2 = pola.keys(); + JSONObject jo2 = null; + while (k2.hasNext()) { + String key2 = (String) k2.next(); + jo2 = pola.getJSONObject(key2); + ret = find_element( jo2, seek_key, seek_value ); + if( ret != null ) { + Log.d("my_debug", "znalazlem element, id: "+ret.getInt("id")); + break; + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + return ret; + } + + protected JSONObject findElementByCodeAndAncestor( String code_to_find, String ancestor_id ) { + JSONObject jo = null; + JSONObject ancestor_jo = find_element_from_Array(js, ancestor_id); + if( ancestor_jo != null ) { + jo = find_element(ancestor_jo, "kod", code_to_find); + } + return jo; + } + + protected JSONObject find_element(JSONObject pola, String id) { + return find_element(pola, "id", id); + } + + protected JSONObject find_element(JSONObject pola, String seek_key, String seek_value) { + try { + //Log.d("my_debug", "finding"); + if( pola.has("id") ) { + //Log.d("my_debug", "finding, id:"+pola.getInt("id")+", given id: "+id); + } + if( pola.has(seek_key) && pola.getString(seek_key).equals(seek_value) ) { + return pola; + } + JSONArray ja = pola.getJSONArray(STRUCT_CHILDS); + //JSONArray temp; + if( ja!= null && ja.length()>0){ + //Log.d("my_debug", STRUCT_CHILDS); + JSONObject find = null; + for ( int i=0; i0){ + + String last = ja.getJSONObject(0).getString("id_wiersz_szablonu"); + + //llh.setOrientation(LinearLayout.VERTICAL); + // po kolumnach ! (nie po wierszach) +// Map> tab = new HashMap>(); +// HashMap temp = new HashMap(); + HashMap> tab = new HashMap>(); + HashMap tab_opisy = new HashMap(); + + + int w = 0; // nr kolumny + int k = 0; // nr wiersza + int ile_kolumn = 0; + + // budowanie tablicy z danymi + for ( int i=0; i temp = new HashMap(); + if( tab.get(k) != null ) { + //Log.d("my_debug", "pobieram, w: "+w+", k: "+k+", temp: "+tab.get(k)); + temp = tab.get(k); + + } + temp.put(w, jElem); + tab.put(k, temp); + last = jElem.getString("id_wiersz_szablonu"); + w++; + } + } + + ile_kolumn += 1; + int ile_wierszy = w; + + + + Log.d("my_debug", "opis: "+jo.getString(STRUCT_OPIS)+", ilosc_wierszy: "+ile_wierszy);//+", tab: "+tab); + + + + // wyświetlanie nagłówków kolumn + TableRow tr_opisy = new TableRow(this); + tr_opisy.setPadding(0, 0, 0, 2); // + tl.addView(tr_opisy); + for (int j = 0 ; j < tab_opisy.size() ; j++ ) { + LinearLayout llh_opis = new LinearLayout(this); + + TableRow.LayoutParams llp = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); + llp.setMargins(0, 0, 2, 0);//2px right-margin + llh_opis.setBackgroundColor(Color.LTGRAY); + llh_opis.setLayoutParams(llp);//2px border on the right for the cell + + tr_opisy.addView(llh_opis); + TextView tw = new TextView(this); + llh_opis.addView(tw); + + if( tab_opisy.get(j) != null ) { + tw.setText( Html.fromHtml(tab_opisy.get(j)) ); + } + } + + ArrayList temp_ostatni_wiersz = new ArrayList(); + + // wyĹ›wietlanie zawartoĹ›ci tabeli + for (int j = 0 ; j < ile_wierszy ; j++ ) { + TableRow tr = new TableRow(this); + tl.addView(tr); + for (int i = 0 ; i < ile_kolumn ; i++ ) { + + LinearLayout llh = new LinearLayout(this); + tr.addView(llh); + llh.setBackgroundColor(Color.BLUE); + //tw.addView(llh); + if( tab.get(i) != null && tab.get(i).get(j) != null) { + wyswietlPole(llh, tab.get(i).get(j), false, enable); + + //Log.d("my_debug", "j: "+j+", size: "+tab.size()+" wart: "+tab.get(i).get(j).getString(STRUCT_WARTOST)); + if( j == ile_wierszy - 1 ) { //komĂłrka z ostatniego wiersz'a + //Log.d("my_debug", "wlazlem ostatni wiersz"); + temp_ostatni_wiersz.add(tab.get(i).get(j).getInt("id")); + } + } + + } + } + + //Log.d("my_debug", STRUCT_OPIS+jo.getString(STRUCT_OPIS)+", temp_ostatni_wiersz: "+temp_ostatni_wiersz); + if( temp_ostatni_wiersz != null && temp_ostatni_wiersz.size() > 0 ) { + tabela_ostatni_wiersz.put(jo.getInt("id"), temp_ostatni_wiersz); + } + // + + } + + Log.d("DedalActivity", jo.toString()); + + // wyswietlanie przycisków dodaj wiersz i usuń wiersz + if( enable && ( jo.has(STRUCT_KLIENT) && !jo.getString(STRUCT_KLIENT).equals("tak") ) ) { + + //LinearLayout new_rows = new LinearLayout(this); + //new_rows.setOrientation(LinearLayout.VERTICAL); + //ll.addView(new_rows); + + Opcje op = new Opcje(jo); + if( !(op.check_opcje("simple_line")) ) { + LinearLayout buttons = new LinearLayout(this); + buttons.setOrientation(LinearLayout.HORIZONTAL); + +// if( !js.has("sub") ) { + + Button bu = new Button(this); + bu.setText( res.getString(R.string.dodaj_wiersz) ); + OnClickListener nClickL = new Dodaj_wiersz(tl, jo); + bu.setOnClickListener(nClickL); + buttons.addView(bu); + + Button bu2 = new Button(this); + bu2.setText( res.getString(R.string.usun_wiersz) ); + OnClickListener nClickL2 = new Usun_wiersz(tl, jo); + bu2.setOnClickListener(nClickL2); + buttons.addView(bu2); + + ll.addView(buttons); + } + } + } + + protected void wyswietl_checkbox(LinearLayout ll, JSONObject jo, Boolean withOpis, Boolean enable ) throws JSONException{ + wyswietl_checkbox(ll, jo, withOpis, enable, null ); + } + + protected ScrollView sw; + protected void wyswietl_checkbox(LinearLayout ll, JSONObject jo, Boolean withOpis, Boolean enable, final String status_interwencji ) throws JSONException{ + + //checkbox + CheckBox cb = new CheckBox(DedalActivity.this); + + cb.setTextSize(25); + if( isGrey) { + cb.setBackgroundColor(Color.LTGRAY); + } + +// cb.setScaleX(1.5f); +// cb.setScaleY(1.5f); +// + ViewGroup.LayoutParams params = cb.getLayoutParams(); + + LinearLayout.LayoutParams mlp = new LinearLayout.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT); +// +// +// // Set left, top, right and bottom margins of Flex CheckBox + mlp.setMargins(5,5,5,5); + cb.setLayoutParams(mlp); +// +// // Apply right padding of Flex CheckBox + cb.setPadding(0,5,5,0); // było 5,5,5,5 + + //toggle button + //ToggleButton cb = new ToggleButton(DedalActivity.this); + + // button +// Button cb = new Button(DedalActivity.this); +// cb.setBackgroundResource(android.R.drawable.button_onoff_indicator_off); +// cb.setPadding(10,0,10, 0); + + if( jo.getString(STRUCT_KLIENT).equals("tak")){ + cb.setClickable(false); + } + +// RelativeLayout.LayoutParams chkBoxParams = new RelativeLayout.LayoutParams( +// // LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); +// 100, 100); +// +// cb.setLayoutParams(chkBoxParams); +// cb.setGravity(Gravity.CENTER); +// cb.setTextColor(Color.BLACK); + + + cb.setText(jo.getString(STRUCT_OPIS)); + //cb.setTextOff(jo.getString(STRUCT_OPIS)); + //cb.setTextOn(jo.getString(STRUCT_OPIS)); + + + cb.setId(jo.getInt("id")); + cb.setMinimumWidth(200); + + if( !enable ) { + cb.setEnabled(false); + } + + if( jo.getString(STRUCT_WARTOSC).equals("on")) { + cb.setChecked(true); + //cb.setBackgroundResource(android.R.drawable.button_onoff_indicator_on); + }else{ + if( !enable ) { return;} // nie wyswietlaj, gdy nie jest zaznaczony checkbox + } + if( jo.getString(STRUCT_KLIENT).equals("tak")){ + //cb.setClickable(false); + cb.setEnabled(false); + }else + cb.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + + y = sw.getScrollY(); + Log.d("my_debug", "Kliknięto check id: " + v.getId()); + setModified(); + //Checkox c = (CheckBox) v; + boolean checked = ((CheckBox) v).isChecked(); + //boolean checked = ((ToggleButton) v).isChecked(); + LinearLayout subView = groupContainer.get(v.getId()); + subView.removeAllViews(); + + v.requestFocusFromTouch(); //prevents from loosing focus and scrolling view down + if (checked) { + + Log.d("my_debug", "check!" ); + //JSONArray ja = jo.getJSONArray(STRUCT_CHILDS); + JSONArray ja2 = checkJson.get(v.getId()); + if( ja2!= null && ja2.length()>0){ + for ( int i=0; i0){ + checkJson.put(bId, ja); + } + LinearLayout llv = new LinearLayout(DedalActivity.this); + llv.setOrientation(LinearLayout.VERTICAL); + + if( ja!= null && ja.length()>0){ + JSONObject jb =ja.getJSONObject(0); + Opcje op = new Opcje(jb); + if( op.check_opcje("fragment")){ + llv.setOrientation(LinearLayout.HORIZONTAL); + // ll.setOrientation(LinearLayout.HORIZONTAL); + LinearLayout lln = new LinearLayout(DedalActivity.this); + lln.setOrientation(LinearLayout.HORIZONTAL); + ll.addView(lln); + ll = lln; + } + } + + ll.addView(cb); + + + if( jo.getString(STRUCT_WARTOSC).equals("on")) { + wyswietl_Dzieci(llv, jo, withOpis, enable, status_interwencji); + } + + ll.addView(llv); + + groupContainer.put(jo.getInt("id"), llv); + } + + protected void wyswietl_radiolista(LinearLayout ll, JSONObject jo, Boolean withOpis, Boolean enable ) throws JSONException{ + wyswietl_radiolista(ll, jo, withOpis, enable, null ); + } + + String status_interwencji_temp = null; + + protected void wyswietl_radiolista(LinearLayout ll, JSONObject jo, Boolean withOpis, Boolean enable, String status_interwencji ) throws JSONException{ + LinearLayout ll_wrapper = new LinearLayout(DedalActivity.this); + ll_wrapper.setOrientation(LinearLayout.VERTICAL); + ll.addView(ll_wrapper); + + wyswietlOpis(ll_wrapper, jo); + RadioGroup rg = new RadioGroup(DedalActivity.this); + if( !enable ) { + rg.setEnabled(false); + } + Opcje op = new Opcje(jo); + //String opcje = jo.getString(STRUCT_OPCJE); + if( op.check_opcje("zakladka") || op.check_opcje("col") ){ + rg.setOrientation(LinearLayout.HORIZONTAL); + }else{ + rg.setOrientation(LinearLayout.VERTICAL); + } + Integer idG =jo.getInt("id"); + rg.setId(idG); + + if( jo.getString(STRUCT_KLIENT).equals("tak")){ + rg.setBackgroundColor(Color.LTGRAY); + } + + LinearLayout llv = new MLinearLayout(DedalActivity.this); + llv.setOrientation(LinearLayout.VERTICAL); + llv.setPadding(20, 0, 0, 0); +// llv.setBackgroundColor(); + if( jo.getString(STRUCT_KLIENT).equals("tak") || !enable){ + llv.setBackgroundColor(Color.parseColor("#B0E0E6")); + } + if( enable){ + llv.setBackgroundColor(Color.parseColor("#FAFAD2")); + } + + radiogroups.put(jo.getInt("id"), new ArrayList()); + ll_wrapper.addView(rg); + + JSONArray ja = jo.getJSONArray(STRUCT_CHILDS); + String selected = jo.getString(STRUCT_WARTOSC); + if( ja!= null && ja.length()>0){ + // sprawdzanie czy w radiobuttonach jest jakiś z opcją referencja + JSONObject radio_ref_jo = null; + for ( int i=0; i0){ + radioJson.put(bId, ja2); + } + + + if( selected.equals(wiersz_szablonu)){ + if( rb instanceof RadioButton) { + ((RadioButton)rb).setChecked(true); + wyswietl_Dzieci(llv, jo2, withOpis, enable, status_interwencji); + + }else{ + // rb.setBackgroundColor(Color.BLUE); //todo. + rb.setBackgroundResource(android.R.drawable.button_onoff_indicator_on); + if( !enable) { // wyświetl dzieci, jak jest tylko podgląd. + wyswietl_Dzieci(llv, jo2, withOpis, enable, status_interwencji); + } + } + }else{ + } + + + } + + if( radio_ref_jo != null ) { + if( !selected.equals(radio_ref_jo.getString(STRUCT_WIERSZ_SZABLONU)) ) { + Log.d("my_debug", "set onload invisible"); + supportOnLoadReferences = radio_ref_jo; + //supporRadioRef(radio_ref_jo, View.GONE); + } + } + } + + //Integer nId = lastId++; + // llv.setId(nId); + ll_wrapper.addView(llv); + groupContainer.put(idG, llv); + + + } + protected void wyswietl_attach(LinearLayout ll, JSONObject jo, String powtarzalny, Boolean enable ) throws JSONException{ + String kat; + if ( powtarzalny.equals(STRUCT_POWTARZALNY) ) { + kat = Integer.toString( jo.getInt("id") ); + } + else { + kat = jo.getString("kod"); + } + if ( enable ) { + ShortButton b = new ShortButton(this); + b.getButton().setText( res.getString(R.string.zrob_zdjecie) ); + b.getButton().setOnClickListener(new ZrobZdjecieListener(kat)); + ll.addView(b.getLinearLayout()); + } + File dir = new File(prefs.getString("dir", "") + "/mDedal/"+m_id+"/"+kat); + Log. d("my_debug", "path: "+prefs.getString("dir", "") + "/mDedal/"+m_id+"/"+kat); + if( dir.isDirectory()){ + File fs[] = dir.listFiles(); + if( fs != null && fs.length>0){ + for( int i=0; i destWidth) { + // picture is wider than we want it, we calculate + // its target height + int destHeight = origHeight + / (origWidth / destWidth); + // we create an scaled bitmap so it reduces the + // image, not just trim it + + bitmap = Bitmap.createScaledBitmap(bitmap, + destWidth, destHeight, false); + } + iw.setImageBitmap(bitmap); + } + } catch (Exception ex){ + Log.e("BITMAP", "plik uszkodzony: " + oFU.getPath()); + return; + } + + + // iw.set + ll.addView(iw); + LinearLayout llv = new LinearLayout(this); + llv.setOrientation(LinearLayout.HORIZONTAL); + ll.addView(llv); + + TextView tw3 = new TextView(this); +// Linkify.addLinks(tw3, mask); + tw3.setText( res.getString(R.string.zdjecie)+": " + file.getName()); + if( file.getName().contains(".pdf")){ + Button bu = new Button(this); + bu.setText("Wyswietl PDF"); + + OnClickListener nClickL = new OnClickListener() { + String m_file = file.getAbsolutePath(); + //String m_for_update = m_file.replace("mDedal", "upload") + ".del"; + @Override + public void onClick(View v) { + File f = new File(m_file); + PackageManager packageManager = getPackageManager(); + Intent testIntent = new Intent(Intent.ACTION_VIEW); + testIntent.setType("application/pdf"); + List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY); + if (list.size() > 0 && f.isFile()) { + Intent intent = new Intent(); + intent.setAction(Intent.ACTION_VIEW); + Uri uri = Uri.fromFile(f.getAbsoluteFile()); + intent.setDataAndType(uri, "application/pdf"); + startActivity(intent); + } + }}; + + bu.setOnClickListener(nClickL); + llv.addView(bu); + } + llv.addView(tw3); + + //button usun zdjÄ™cie + if ( enable ) { + Button bu = new Button(this); + bu.setText( res.getString(R.string.usun_zdjecie) ); + + OnClickListener nClickL = new OnClickListener() { + String m_file = file.getAbsolutePath(); + String m_for_update = m_file.replace("mDedal", "upload") + ".del"; + @Override + public void onClick(View v) { + // usun plik + File fusun = new File(m_file); + File fUpload = new File(m_for_update); + fusun.renameTo(fUpload); + //fusun.delete(); + + // todo: tymczasowe zakomentowanie + //DedalActivity.this.recreate(); + reload(); + }}; + + bu.setOnClickListener(nClickL); + llv.addView(bu); + } + + } + } + } + + //File myFile = new File(Environment.getExternalStorageDirectory() + "/mDedal/"+m_id+"/"+ fileName); + + //File file = new File(Environment.getExternalStorageDirectory(), "test.jpg"); + + } + + protected void wyswietl_foto(LinearLayout ll, JSONObject jo, Boolean enable ) throws JSONException{ +// String typ_danych = jo.getString(STRUCT_TYP_DANYCH); +// TextView tw2 = new TextView(this); +// tw2.setText("typ: to jest " + typ_danych); +// ll.addView(tw2); + + Log.d("my_debug", "wyswietl_foto"); + + //String kod = jo.getString("kod"); + String wartosc = jo.getString(STRUCT_WARTOSC); + + if ( !first_foto_displayed && enable ) { + //if(jo.getInt("id") == ostatni_powtarzalny.get(jo.getInt("parent")).get(jo.getInt("id_wiersz_szablonu"))) { + Button b = new Button(this); + b.setText( res.getString(R.string.zrob_zdjecie) ); + b.setOnClickListener(new ZrobZdjecieListener("foto_typ")); + ll.addView(b); + } + + // wyďż˝wietlanie zdj�� przed chwilďż˝ zrobionych + if ( !first_foto_displayed ) { + File dir_upload = new File(prefs.getString("dir", "") + "/upload/"+m_id+"/foto_typ"); + + if( dir_upload.isDirectory()){ + File fs[] = dir_upload.listFiles(); + if( fs != null && fs.length>0){ + //File f_file; + Bitmap bitmap; + for( int i=0; i destWidth) { + // picture is wider than we want it, we calculate + // its target height + int destHeight = origHeight + / (origWidth / destWidth); + // we create an scaled bitmap so it reduces the + // image, not just trim it + + bitmap = Bitmap.createScaledBitmap(bitmap, + destWidth, destHeight, false); + } + } + iw_t.setImageBitmap(bitmap); + + //iw.set + ll.addView(iw_t); + LinearLayout llv_t = new LinearLayout(this); + llv_t.setOrientation(LinearLayout.HORIZONTAL); + ll.addView(llv_t); + + TextView tw3_t = new TextView(this); + tw3_t.setText(res.getString(R.string.zdjecie) + ": " + file.getName()); + //tw3.setText("zdjÄ™cie: " + wartosc); + llv_t.addView(tw3_t); + + //button usun zdjďż˝cie + Button bu_t = new Button(this); + bu_t.setText( res.getString(R.string.usun_zdjecie) ); + OnClickListener nClickL_t = new OnClickListener() { + File file_loc = new File(file.getAbsolutePath()); + @Override + public void onClick(View v) { + file_loc.delete(); + + reload(); + }}; + + bu_t.setOnClickListener(nClickL_t); + llv_t.addView(bu_t); + } + + } + } + } + } + +// + + File dir = new File(prefs.getString("dir", "") + "/mDedal/"+m_id+"/foto_typ"); + Log.d("my_debug", "path: "+prefs.getString("dir", "") + "/mDedal/"+m_id+"/foto_typ"); + Log.d("my_debug", "dir: "+dir); + if( dir.isDirectory()){ + File file_te = new File(prefs.getString("dir", "") + "/mDedal/"+m_id+"/foto_typ/"+wartosc); + file = file_te; + + Log.d("my_debug", "file: "+file); + + Uri oFU = Uri.fromFile(file); + + ImageView iw = new ImageView(this); + +// Bitmap bitmap = BitmapFactory.decodeFile(oFU.getPath()); + byte [] bytes = DedalHelper.getCryptFileContent(file.getAbsolutePath()).getBytes(); + Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); + + if( bitmap != null){ + int origWidth = bitmap.getWidth(); + int origHeight = bitmap.getHeight(); + + final int destWidth = 300;//or the width you need + + if(origWidth > destWidth){ + // picture is wider than we want it, we calculate its target height + int destHeight = origHeight/( origWidth / destWidth ) ; + // we create an scaled bitmap so it reduces the image, not just trim it + bitmap = Bitmap.createScaledBitmap(bitmap, destWidth, destHeight, false); + } + + iw.setImageBitmap(bitmap); + + ll.addView(iw); + } + LinearLayout llv = new LinearLayout(this); + llv.setOrientation(LinearLayout.HORIZONTAL); + ll.addView(llv); + + TextView tw3 = new TextView(this); + + if( file.getName().contains(".pdf")){ + Button bu = new Button(this); + bu.setText("Wyswietl PDF"); + + OnClickListener nClickL = new OnClickListener() { + String m_file = file.getAbsolutePath(); + //String m_for_update = m_file.replace("mDedal", "upload") + ".del"; + @Override + public void onClick(View v) { + File f = new File(m_file); + PackageManager packageManager = getPackageManager(); + Intent testIntent = new Intent(Intent.ACTION_VIEW); + testIntent.setType("application/pdf"); + List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY); + if (list.size() > 0 && f.isFile()) { + Intent intent = new Intent(); + intent.setAction(Intent.ACTION_VIEW); + Uri uri = Uri.fromFile(f.getAbsoluteFile()); + //todo: change to internet access to DEDAL + intent.setDataAndType(uri, "application/pdf"); + startActivity(intent); + } + }}; + + bu.setOnClickListener(nClickL); + llv.addView(bu); + } + + if(file.exists()) { + //tw3.setText("zdjďż˝cie: " + file.getName()); + tw3.setText(res.getString(R.string.zdjecie)+": " + wartosc); + llv.addView(tw3); + //button usun zdjďż˝cie + if( !wartosc.equals("") && enable ) { + Button bu = new Button(this); + bu.setText( res.getString(R.string.usun_zdjecie) ); + + OnClickListener nClickL = new OnClickListener() { + String m_file = file.getAbsolutePath(); + String m_for_update = m_file.replace("mDedal", "upload") + ".del"; + @Override + public void onClick(View v) { + + Log.d("my_debug", "usuwam, m_file:"+ m_file+", m_for_update: " + m_for_update ); + // usun plik + File fusun = new File(m_file); + File fUpload = new File(m_for_update); + fusun.renameTo(fUpload); + // todo: tymczasowe zakomentowanie + //DedalActivity.this.recreate(); + reload(); + }}; + + bu.setOnClickListener(nClickL); + llv.addView(bu); + } + } + + //} + //} + } + if ( !first_foto_displayed ) { + first_foto_displayed = true; + } + //File myFile = new File(Environment.getExternalStorageDirectory() + "/mDedal/"+m_id+"/"+ fileName); + + //File file = new File(Environment.getExternalStorageDirectory(), "test.jpg"); + + } + + protected void wyswietl_special(LinearLayout ll, JSONObject jo, Boolean withOpis, Boolean enable ) throws JSONException{ + + LinearLayout llv = ll; + String typ_danych = jo.getString(STRUCT_TYP_DANYCH); + String opcje = jo.getString(STRUCT_OPCJE); + if( withOpis) { + // + ll = new LinearLayout(this); +// ll.setBackgroundColor(Color.MAGENTA); +// if ( "nr_tel_mail".equals(opcje) ){ +// ll.setOrientation(LinearLayout.VERTICAL); +// } +// else { + ll.setOrientation(LinearLayout.HORIZONTAL); + //} + llv.addView(ll); + //} + wyswietlOpis(ll, jo); + } + if( opcje.equals("dokumenty_fin") || + opcje.equals("adres_dodatkowy")|| + opcje.equals("nr_tel_mail") ){ + ll.setOrientation(LinearLayout.VERTICAL); + } + //wyswietlOpis(ll, jo); + + + //Log.d("my_debug", "special: typ: "+ opcje); + + if( "adres_podst".equals(opcje)){ + JSONObject adres = js.getJSONObject("adres_podst"); + String adr = adres.getString("kod_pocztowy")+ " " + adres.getString("miasto") + + " " + adres.getString("miejscowosc") + + " ul. " + adres.getString("ulica") + + " " + adres.getString("nr_domu"); +// TextView two = new TextView(this); +// two.setText(adr); +// ll.addView(two); + wyswietl_text_ramka(ll, adr); + }else if("adres_dodatkowy".equals(opcje)) { +// JSONArray ja = js.getJSONArray("adresy_dodatkowe"); +// if( ja!= null && ja.length()>0){ +// for ( int i=0; i0){ +// for ( int i=0; i0){ +// for ( int i=0; i0){ + for ( int i=0; i(); + dluznikItems_id_dluznik = new ArrayList(); + Log.d("my_debug", "ja_dluznicy.lenght: " + ja_dluznicy.length()); + for( int i = 0 ; i < ja_dluznicy.length() ; i++ ) { + + JSONObject jo_dluznik = ja_dluznicy.getJSONObject(i); + + // wypełnienie tabeli globalnej aby można było wypełnić spinnera do wyboru dłużnika w interwencji + if( jo_dluznik.has("imie_nazwisko") && !"".equals(jo_dluznik.getString("imie_nazwisko")) ) { + dluznikItems_names.add(jo_dluznik.getString("imie_nazwisko")); + } + else if( jo_dluznik.has("nazwa_firmy") && !"".equals(jo_dluznik.getString("nazwa_firmy")) ) { + dluznikItems_names.add(jo_dluznik.getString("nazwa_firmy")); + } + dluznikItems_id_dluznik.add(jo_dluznik.getString("id")); + + Log.d("my_debug", "aktywny: "+jo_dluznik.getString("aktywny")); + +// if( !jo_dluznik.has("aktywny") || !"1".equals(jo_dluznik.getString("aktywny")) ) { +// continue; +// } + //Log.d("my_debug", "aktywny: "+jo_dluznik.getString("aktywny")); + Log.d("my_debug", "key: "+i); + LinearLayout ll_dluznik = new BorderLinearLayout(this); + ll_dluznicy.addView(ll_dluznik); + ll_dluznik.setOrientation(LinearLayout.VERTICAL); + ll_dluznik.setPadding(5,5,5,5); + LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); + layoutParams.setMargins(0, 0, 0, 20); + ll_dluznik.setLayoutParams(layoutParams); + + TextView tv_imie_nazwisko = new TextView(this); + tv_imie_nazwisko.setTextSize(dluznicy_text_size+4); + ll_dluznik.addView(tv_imie_nazwisko); + tv_imie_nazwisko.setText(Html.fromHtml("Imie i nazwisko: "+jo_dluznik.getString("imie_nazwisko")+"")); + + TextView tv_nazwa_firmy = new TextView(this); + tv_nazwa_firmy.setTextSize(dluznicy_text_size); + ll_dluznik.addView(tv_nazwa_firmy); + tv_nazwa_firmy.setText(Html.fromHtml("Nazwa firmy: "+jo_dluznik.getString("nazwa_firmy")+"")); + + TextView tv_pesel = new TextView(this); + tv_pesel.setTextSize(dluznicy_text_size); + ll_dluznik.addView(tv_pesel); + tv_pesel.setText(Html.fromHtml("PESEL: "+jo_dluznik.getString("pesel")+"")); + + TextView tv_nr_dowodu = new TextView(this); + tv_nr_dowodu.setTextSize(dluznicy_text_size); + ll_dluznik.addView(tv_nr_dowodu); + tv_nr_dowodu.setText(Html.fromHtml("Nr dowodu: "+jo_dluznik.getString("nr_dowodu")+"")); + + TextView tv_nip = new TextView(this); + tv_nip.setTextSize(dluznicy_text_size); + ll_dluznik.addView(tv_nip); + tv_nip.setText(Html.fromHtml("NIP: "+jo_dluznik.getString("nip")+"")); + + if( jo_dluznik.has("adresy") ) { + wyswietl_adresy(ll_dluznik, jo_dluznik.getJSONArray("adresy"), dluznicy_text_size, Typeface.BOLD ); + } + + if( jo_dluznik.has("telefony") ) { + wyswietl_telefony(ll_dluznik, jo_dluznik.getJSONArray("telefony"), dluznicy_text_size, Typeface.BOLD); + } + + //break; + } + +// Iterator k = jo_dluznicy.keys(); +// while (k.hasNext()) { +// String key = (String) k.next(); +// +// JSONObject jo_dluznik = jo_dluznicy.getJSONObject(key); +// Log.d("my_debug", "aktywny: "+jo_dluznik.getString("aktywny")); +// if( !jo_dluznik.has("aktywny") || !"1".equals(jo_dluznik.getString("aktywny")) ) { +// continue; +// } +// //Log.d("my_debug", "aktywny: "+jo_dluznik.getString("aktywny")); +// Log.d("my_debug", "key: "+key); +// LinearLayout ll_dluznik = new LinearLayout(this); +// ll_dluznicy.addView(ll_dluznik); +// ll_dluznik.setOrientation(LinearLayout.VERTICAL); +// +// TextView tv_imie_nazwisko = new TextView(this); +// ll_dluznik.addView(tv_imie_nazwisko); +// tv_imie_nazwisko.setText("Imie i nazwisko: "+jo_dluznik.getString("imie_nazwisko")); +// +// TextView tv_nazwa_firmy = new TextView(this); +// ll_dluznik.addView(tv_nazwa_firmy); +// tv_nazwa_firmy.setText("Nazwa firmy: "+jo_dluznik.getString("nazwa_firmy")); +// +// break; +// } + + } + } + + protected void wyswietl_adresy(LinearLayout ll, JSONArray ja) { + wyswietl_adresy(ll, ja, 0, 0); + } + + protected void wyswietl_adresy(LinearLayout ll, JSONArray ja, int text_size, int typeface_style) { + TableLayout tl = new TableLayout(this); + tl.setPadding(0, 15, 0, 0); + ll.addView(tl); + TableRow tr_opisy = new TableRow(this); + tr_opisy.setPadding(0, 0, 0, 2); // + tl.addView(tr_opisy); + + // NAGŁÓWKI + TextView tw[] = new TextView[7]; + for( int i = 0 ; i < 7 ; i++ ) { + LinearLayout llh_opis = new LinearLayout(this); + + TableRow.LayoutParams llp = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); + llp.setMargins(0, 0, 2, 0);//2px right-margin + llh_opis.setBackgroundColor(Color.LTGRAY); + llh_opis.setLayoutParams(llp);//2px border on the right for the cell + + tr_opisy.addView(llh_opis); + tw[i] = new TextView(this); + llh_opis.addView(tw[i]); + + } + tw[0].setText("Kod");tw[1].setText("Miasto");tw[2].setText("Miejscowość");tw[3].setText("Ulica");tw[4].setText("Numer domu");tw[5].setText("Zweryfikowany?");tw[6].setText("Typ adresu"); + + // ZAWARTOŚĆ + try { + LinearLayout llh[] = new LinearLayout[7]; + if( ja!= null && ja.length()>0){ + for ( int i=0; i0){ + for ( int i=0; i 0 ) { + two.setTextSize(text_size); + } + two.setTypeface(null, typeface_style); // 0 is normal + + ll.addView(two); + } + + + public String foto_kod = null; + public String foto_name = null; + + + protected final class DokKollektoBtnListener implements OnClickListener { + + String id_zlecenia; + JSONArray dkJson; + + public DokKollektoBtnListener(String id_zlecenia, JSONArray dkJson) { + this.id_zlecenia = id_zlecenia; + this.dkJson = dkJson; + } + + @Override + public void onClick(View v) { + Log.d("my_debug", "click Dokumenty Kollekto, id_zlecenia: "+id_zlecenia); + Intent intent = new Intent(DedalActivity.this, getDokumentyKollektoActivity()); + intent.putExtra("id_zlecenia", id_zlecenia); + intent.putExtra("dkJson", dkJson.toString()); + startActivity(intent); + } + } + + protected final class Ustaw_date implements OnClickListener { + String opcje; + public Ustaw_date(String opcje) { + this.opcje = opcje; + } + + @Override + public void onClick(View v) { + cur_Date_id = ((ButtonDate)v).getEdId(); + //EditText et = (EditText)DedalActivity.this.findViewById(cur_Date_id); + //et.setText("00"); + cur_Date_opcje = this.opcje; + showDialog(DATE_DIALOG_ID); + } + } + + protected final class Dodaj_wiersz implements OnClickListener { + + TableLayout tl; + JSONObject jo; + + public Dodaj_wiersz(TableLayout tl, JSONObject jo) { + this.tl= tl; + this.jo = jo; + } + + @Override + public void onClick(View v) { + Log.d("my_debug", "onclick: dodaj wiersz"); + //Log.d("my_debug", "jo: "+jo.toString()); + try { + setModified(); + //Log.d("my_debug", "tabela_ostatni_wiersz stara: "+tabela_ostatni_wiersz); + + TableRow tr = new TableRow(DedalActivity.this); + tl.addView(tr); + + JSONArray ja = jo.getJSONArray(STRUCT_CHILDS); + LinearLayout llh = null;//new LinearLayout(this); + if( ja!= null && ja.length()>0){ + + String last = "";//ja.getJSONObject(0).getString("id_wiersz_szablonu"); + + //Log.d("my_debug", "ja.length: "+ja.length()); + + //llh.setOrientation(LinearLayout.VERTICAL); + ArrayList temp = new ArrayList(); + for ( int i=0 ; i < ja.length() ; i++){ + JSONObject j = ja.getJSONObject(i); + //Log.d("my_debug", "last: "+last+", id_w_s: "+j.getString("id_wiersz_szablonu")); + + if( !last.equals(j.getString("id_wiersz_szablonu")) && !j.has("id-orig")){ + //Log.d("my_debug","roznee !!!!!!!!!!"); + llh = new LinearLayout(DedalActivity.this); + tr.addView(llh); + + JSONObject newFiled = new JSONObject(j.toString()); +// maxId++; +// newFiled.put("id", maxId); +// newFiled.put(STRUCT_WARTOST, ""); +// newFiled.put("id-orig", j.getInt("id")); + add_id_orig(newFiled); + jo.getJSONArray(STRUCT_CHILDS).put(newFiled); + + // zmiana w tabeli tabela_ostatni_wiersz + //temp.add(maxId); + temp.add(newFiled.getInt("id")); + + /// + //Log.d("my_debug", "dodawanie, typ_danych: "+newFiled.getString(STRUCT_TYP_DANYCH)+", maxId: "+maxId+", id: "+newFiled.getString("id")+", id_orig: "+newFiled.getString("id-orig") ); + wyswietlPole(llh, newFiled, false, true); + + last = j.getString("id_wiersz_szablonu"); + + } + else { + //Log.d("my_debug","rownee"); + } + + + } + Log.d("my_debug", "tabela_wiersz_ostatni stara: " + tabela_ostatni_wiersz.get(jo.getInt("id"))); + if(temp != null && temp.size() > 0) { + tabela_ostatni_wiersz.put(jo.getInt("id"), temp); + } + Log.d("my_debug", "tabela_wiersz_ostatni nowa: " + tabela_ostatni_wiersz.get(jo.getInt("id"))); + } + + napraw_kolejnosc(); + + //Log.d("my_debug", "tabela_ostatni_wiersz nowa: "+tabela_ostatni_wiersz); + //Log.d("my_debug", "jo: "+jo.toString()); + + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + protected void napraw_kolejnosc() { + JSONArray ja; + try { + + ArrayList listdata = new ArrayList(); + ja = jo.getJSONArray(STRUCT_CHILDS); + //JSONArray ja_copy = new JSONArray(ja.toString()); + if( ja!= null && ja.length()>0){ + for ( int i=0 ; i < ja.length() ; i++){ + //JSONObject j = ja.getJSONObject(i); + listdata.add(ja.getJSONObject(i)); + } + } + sortujKolejnosc(listdata); + JSONArray sorted_ja = new JSONArray(listdata); + jo.remove(STRUCT_CHILDS); + jo.put(STRUCT_CHILDS, sorted_ja); + //ja = sorted_ja; + + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + + } + +// private void sortujKolejnosc(ArrayList aM) { +// Collections.sort(aM, new Comparator() { +// @Override +// public int compare(JSONObject lhs, JSONObject rhs) { +// // TODO Auto-generated method stub +// try { +// if( lhs.getInt("kolejnosc") >(rhs.getInt("kolejnosc"))){ +// return 1; +// }else if( lhs.getInt("kolejnosc") < (rhs.getInt("kolejnosc"))){ +// return -1; +// }else{ +// if( lhs.getInt("id") > (rhs.getInt("id"))) +// return 1; +// else if ( lhs.getInt("id") < (rhs.getInt("id"))) +// return -1; +// return 0; +// } +// } catch (JSONException e) { +// // TODO Auto-generated catch block +// //e.printStackTrace(); +// } +// return 0; +// } +// }); +// } + } + + protected final class Usun_wiersz implements OnClickListener { + + // LinearLayout ll; + JSONObject jo; + + public Usun_wiersz(LinearLayout ll, JSONObject jo) { +// this.ll= ll; + this.jo = jo; + } + + @Override + public void onClick(View v) { + try { + setModified(); + if(jo.has("id")) { + int id = jo.getInt("id"); + int ilosc_wierszy = count_rows(); + // gdy ilość wierszy <= 1 ma nie usuwać ! + if( ilosc_wierszy > 1 ) { + usun_pola_json(); + if( tabela_ostatni_wiersz != null && tabela_ostatni_wiersz.get(id) != null ){ + ArrayList temp = tabela_ostatni_wiersz.get(id); + for( int i = 0 ; i < temp.size() ; i++) { + + Log.d("my_debug", "usuwam, id: "+temp.get(i)); + View element = DedalActivity.this.findViewById(temp.get(i)); + + if( element != null ) { + Log.d("my_debug", "znalazłem, id: "+temp.get(i)); + element.setVisibility(View.GONE); //invisible + } + } + } + set_tabela_ostatni_wiersz(); + + } + } + + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + protected int count_rows() { + JSONArray ja; + int ilosc_wierszy = 0; + try { + ja = jo.getJSONArray(STRUCT_CHILDS); + if( ja!= null && ja.length()>0){ + String last = ja.getJSONObject(0).getString("id_wiersz_szablonu"); + //ArrayList temp = new ArrayList(); + //boolean has_usun = false; + ilosc_wierszy = 1; + for ( int i=1; i0){ + String last = "";//ja.getJSONObject(0).getString("id_wiersz_szablonu"); + ArrayList temp = new ArrayList(); + boolean has_usun = false; + for ( int i=0; i 0 && temp.size() > i_temp ) { + if(j.has("id") && !j.has("usun")) { + temp.set(i_temp, j.getInt("id")); + } + } + else { + if(j.has("id") && !j.has("usun")) { + temp.add( j.getInt("id")); + } + } + + //Log.d("my_debug", "last: "+last+", j_next : "+j_next.getString("id_wiersz_szablonu")); + if( !last.equals(j_next.getString("id_wiersz_szablonu") ) ) { + i_temp++; + //Log.d("my_debug", "zwiekszam i_temp: "+i_temp); + } + + } + //} + } + + +// if( i+1 < ja.length() ) { +// JSONObject j_next = ja.getJSONObject(i+1); +// // jeĹ›li nastÄ™pny element jest pierwszym elementem kolumny to znaczy ĹĽe ten element jest ostatnim elementem kolumny +// if(j.has("id")) { +// if( !j_next.has("id") || j_next.has("usun") ) { +// temp.add(j.getInt("id")); +// czy_ostatni = true; +// has_usun = true; +// } +// else +// if( !last.equals(j_next.getString("id_wiersz_szablonu")) && !has_usun){ +// czy_ostatni = true; +// temp.add(j.getInt("id")); +// } +// } +// } + +// else { +// if( !has_usun ){ +// czy_ostatni = true; +// } +// } + //Log.d("my_debug", "id: "+j.getInt("id")+", has_usun: "+has_usun); + if(czy_ostatni) { + + } + } + Log.d("my_debug", "tabela_wiersz_ostatni stara: " + tabela_ostatni_wiersz.get(jo.getInt("id"))); + if(temp != null && temp.size() > 0) { + tabela_ostatni_wiersz.put(jo.getInt("id"), temp); + } + Log.d("my_debug", "tabela_wiersz_ostatni nowa: " + tabela_ostatni_wiersz.get(jo.getInt("id"))); + } + + + + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + + } + + protected void usun_pola_json() { + JSONArray ja; + try { + int id = jo.getInt("id"); + ja = jo.getJSONArray(STRUCT_CHILDS); + // przeszukiwanie po polach tabeli + if( ja!= null && ja.length()>0){ + for ( int i=0; i temp = tabela_ostatni_wiersz.get(id); + // sprawdzanie czy dane pole jest z ostatniego wiersza + for( int j = 0 ; j < temp.size() ; j++) { + // znaleziony element jest z ostatniego wiersza + //Log.d("my_debug", "elem.int: "+) + if( elem.has("id") && elem.getInt("id") == temp.get(j) ) { + if( !elem.has("id-orig") ) { + //jo.put("id", jo.getInt("id")+"-usun"); + //Log.d("my_debug", "usuwam dobre: id: "+elem.getInt("id")); + elem.put("usun", "true"); + } + if( elem.has("id-orig") ) { + if( js.has("sub") ) { + elem.put("usun", "true"); + } + else { + elem.remove("id"); + elem.remove("id-orig"); + } + //Log.d("my_debug", "usuwam: id: "+elem.getInt("id")+" id-orig: "+elem.getInt("id-orig")); + + } + } + } + } + } + } + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + + } + } + + + protected final class Walidacja_poprawnosci implements OnFocusChangeListener { + + protected final class Set_focus_runnable implements Runnable { + EditText et; + + public Set_focus_runnable(EditText et) { + this.et = et; + } + + @Override + public void run() { + et.requestFocus(); + + } + } + + String typ_danych; + String walidacja; + + public Walidacja_poprawnosci(String walidacja, String typ_danych) { + this.walidacja = walidacja; + this.typ_danych = typ_danych; + } + + @Override + public void onFocusChange(View v, boolean hasFocus) { + //Log.d("my_debug", "zejscie1"); + try { + EditText et = (EditText) v; + if (!hasFocus) { + String value = et.getText().toString().trim(); + if (!value.equals("")) { + + String pattern = null; + String komunikat = null; + if (walidacja != null && walidacja.equals("kod_pocztowy")) { // kod pocztowy + pattern = "[0-9]{2}-[0-9]{3}"; + if (!value.matches(pattern)) { + komunikat = res.getString(R.string.walid_kod_pocztowy) + ", np. 12-345"; + } + } else if (walidacja != null && walidacja.equals("telefon")) { // telefon + value = value.replaceAll("\\s+", ""); // wycinanie spacji + pattern = "\\+?[0-9,\\(,\\)]*"; + if (!value.matches(pattern)) { + komunikat = res.getString(R.string.walid_nr_telefonu); + } + } else if (typ_danych != null && typ_danych.equals(TYPE_KWOTA)) { // kwota + pattern = "[0-9]{1,}\\,[0-9]{1,2}"; + String pattern2 = "[0-9]{1,}"; + if (!value.matches(pattern) && !value.matches(pattern2)) { + komunikat = res.getString(R.string.walid_kwota) + ", np. 123,45"; + } + + if (walidacja != null && walidacja.trim().length() > 0) { //Mateusz - dodanie warunku walidacji - wielokrotnosc + Integer wielokrotnosc = Integer.parseInt(walidacja); + + if (value != null && TextUtils.isDigitsOnly(value)) { + Integer kwota = Integer.parseInt(value); + if (kwota % wielokrotnosc != 0) { + if (wielokrotnosc == 10) { + komunikat = res.getString(R.string.walid_kwota_wielokrotnosc_10) + ", np. 120"; + } else { + komunikat = res.getString(R.string.walid_kwota_wielokrotnosc); + } + } + } else { + komunikat = res.getString(R.string.walid_kwota_wielokrotnosc) + " kwoty" + wielokrotnosc.toString(); + } + } + + } else if (typ_danych != null && typ_danych.equals(TYPE_LICZBA) && (walidacja == null || walidacja.equals(""))) { // liczba naturalna + pattern = "[0-9]{1,}"; + if (!value.matches(pattern)) { + komunikat = res.getString(R.string.walid_liczba_naturalna) + ", np. 123"; + } + } else if (typ_danych != null && typ_danych.equals(TYPE_LICZBA) && (walidacja != null && walidacja.equals("."))) { // liczba rzeczywista (część uĹ‚amkowa rozdzielona .) + pattern = "[0-9]{1,}\\.[0-9]{1,}"; + if (!value.matches(pattern)) { + komunikat = res.getString(R.string.walid_liczba_rzeczywista) + ", np. 123.4567"; + } + } else if (typ_danych != null && typ_danych.equals(TYPE_LICZBA) && (walidacja != null && walidacja.equals(","))) { // liczba rzeczywista (część uĹ‚amkowa rozdzielona ,) + pattern = "[0-9]{1,}\\,[0-9]{1,}"; + if (!value.matches(pattern)) { + komunikat = res.getString(R.string.walid_liczba_rzeczywista) + ", np. 123,4567"; + } + } + + if (komunikat != null) { + //Log.d("my_debug", "zejscie2"); + AlertDialog.Builder alertDialog = new AlertDialog.Builder(DedalActivity.this); + alertDialog.setTitle("Walidacja formatu"); + alertDialog.setMessage(komunikat); + alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + }); + alertDialog.show(); + + et.post(new Set_focus_runnable(et)); + //et.requestFocus(); + + } + ; + } + + } + //Toast.makeText(getApplicationContext(), "unfocus", 2000).show(); + + }catch( + Exception e) + + { + Log.e("BLAD", "konfiguracja walidacji."); + } + } + } + + public void reload() { + + Intent intent = getIntent(); + overridePendingTransition(0, 0); + intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); + finish(); + + overridePendingTransition(0, 0); + startActivity(intent); + } + + + + protected boolean is_notend_interventions( JSONObject pola) { + + return false; + } + + protected void add_usun_tag(JSONObject jo) { + JSONArray ja; + try { + if( jo.has("id") && !jo.has("id-orig") ) { + //jo.put("id", jo.getInt("id")+"-usun"); + jo.put("usun", "true"); + } + + if( jo.has("id") && jo.has("id-orig") ) { + if( js.has("sub") ) { + jo.put("usun", "true"); + } + else { + jo.remove("id"); + jo.remove("id-orig"); + } + } + + //jo.put(STRUCT_WARTOST, ""); + ja = jo.getJSONArray(STRUCT_CHILDS); + if( ja!= null && ja.length()>0){ + for ( int i=0; i 1 ) { + + if( view != null ) { + Log.d("my_debug", "remove, id: "+id); + //view.onMeasure(0,0); + //((ViewManager)view.getParent()).removeView(view); + view.setVisibility(View.GONE); //invisible + + v.setVisibility(View.GONE); + + + } + else { + Log.d("my_debug", "remove, id: "+id+" is null"); + } + + add_usun_tag(jo); + + if ( ilosc_powtarzalnych.get(jo.getInt("parent")).get(jo.getInt("id_wiersz_szablonu")) != null ) { + HashMap temp = new HashMap(); + temp.put(jo.getInt("id_wiersz_szablonu"), ilosc-1); + ilosc_powtarzalnych.put(jo.getInt("parent"), temp); + //Log.d("my_debug", "zmniejszam, ilosc: "+(ilosc-1)); + } + } + else { + Log.d("my_debug", "nie moĹĽna usunąć ostatniego pola !"); + } + + + + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + } + + protected JSONObject add_id_orig(JSONObject jo) { + + JSONArray ja; + try { + jo.put("id-orig", jo.getInt("id")); + maxId++; + jo.put("id", maxId); + jo.put(STRUCT_WARTOSC, ""); + if( jo.has("usun") ) { + jo.remove("usun"); + } + + ja = jo.getJSONArray(STRUCT_CHILDS); + if( ja!= null && ja.length()>0){ + for ( int i=0; i 1 && parts[1].equals("usun") ) { +// id = Integer.parseInt(parts[0]); +// } +// else { + id = jo.getInt("id"); +// } + + + // Iterator k = pola.keys(); + //JSONObject find = null; + //JSONObject jo = null; + +// EditText et = new EditText(DedalActivity.this); +// et.setText("tralalal"); +// ll.addView(et); + + if( jo != null ) { + //Log.d("my_debug", "find json, id: "+id+", parent: " + jo.getInt("parent")); + Iterator k2 = pola.keys(); + JSONObject parent = null; + JSONObject jo2 = null; + String find_id = null; + while (k2.hasNext()) { + String key2 = (String) k2.next(); + jo2 = pola.getJSONObject(key2); + //Log.d("my_debug", "next val: "+jo.getInt("id")+"key: "+key2); + + find_id = jo.getString("parent"); + + //Log.d("my_debug", "find_id: "+find_id); + parent = find_element( jo2, find_id ); + if( parent != null ) { + Log.d("my_debug", "znalazlem parenta, id: "+parent.getInt("id")); + break; + } + } + if(parent != null) { + JSONObject newFiled = new JSONObject(jo.toString()); + //Log.d("my_debug", "jo-string: "+jo.toString()); + //Log.d("my_debug", "newFiled-string: "+newFiled.toString()); + maxId++; + //int newId = maxId + 1; + //newFiled.put("id", maxId); + add_id_orig(newFiled); + + newFiled.put("id-orig", id); + //parent.put(STRUCT_CHILDS, newFiled); + parent.getJSONArray(STRUCT_CHILDS).put(newFiled); + //Log.d("my_debug", "parent-string: "+parent.toString()); + //Log.d("my_debug", "json: "+js.toString()); + + if ( ilosc_powtarzalnych.get(jo.getInt("parent")).get(jo.getInt("id_wiersz_szablonu")) != null ) { + Integer ilosc = ilosc_powtarzalnych.get(jo.getInt("parent")).get(jo.getInt("id_wiersz_szablonu")); + HashMap temp = new HashMap(); + temp.put(jo.getInt("id_wiersz_szablonu"), ilosc+1); + ilosc_powtarzalnych.put(jo.getInt("parent"), temp); + //Log.d("my_debug", "zwiekszam, ilosc: "+(ilosc+1)); + } + + //newFiled.put("dodaj_nowy", "false"); + wyswietlPole(ll, newFiled ); + } + + + //Log.d("my_debug", "wyswietl, id: "+jo.getInt("id")+", parent: " + jo.getInt("parent")); + setModified(); + } + + + + //Log.d("my_debug", "find json, id: "+jo.getInt("id")); + //Log.d("my_debug", "find json, id: "+jo.getInt("id")+", parent: "+jo.getInt("parent")); + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + //ll.addView(DedalActivity.this.findViewById(v.getId())); + } + } + + + + protected class ZrobZdjecieListener implements OnClickListener { + + + String folder = "empty"; + public ZrobZdjecieListener( String kod ){ + folder = kod; + } + + @Override + public void onClick(View v) { + // zapisanie zdjďż˝cia + //File file = new File(Environment.getExternalStorageDirectory(), "test.jpg"); + +// File fileD = new File(Environment.getExternalStorageDirectory() + "/mDedal/"+m_id+"/"+folder ); +// File fileD = new File(Environment.getExternalStorageDirectory() + "/mDedal" ); +// File fileD = new File(getFilesDir().getAbsolutePath() + "/mDedal/"+m_id+"/"+folder ); + File fileD = new File(prefs.getString("dir", "")+ "/mDedalCam" ); + if( !fileD.isDirectory()){ + fileD.mkdirs(); + } + + Date d = new Date(); + String genName = "foto_"+d.getTime() + ".jpg"; + foto_kod = folder; + foto_name = genName; + + forceDoZapis("sub", "Zapisz zmiany"); + String path = prefs.getString("dir", "")+ "/mDedalCam/" +genName; + + // openCamra( path); +// File file = new File(getFilesDir().getAbsolutePath() + "/mDedal/"+m_id+"/"+folder + "/" +genName); + + StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); + StrictMode.setVmPolicy(builder.build()); + + File file = new File(prefs.getString("dir", "")+ "/mDedalCam/" +genName); + Uri oFU = Uri.fromFile(file); + Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE); //moďż˝e secure? + intent.putExtra(MediaStore.EXTRA_OUTPUT, oFU); + startActivityForResult(intent, TAKE_PICTURE); + } + } + void openCamra(String path) { + StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); + StrictMode.setVmPolicy(builder.build()); + + Intent cameraImgIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); + + cameraImgIntent.putExtra(MediaStore.EXTRA_OUTPUT, + FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID +".provider", + new File(path))); + startActivityForResult(cameraImgIntent, TAKE_PICTURE); + } + protected class ChangeZlecenieFolderSelectedListenerDedalActivity implements + OnItemSelectedListener { + + private int id_zlecenia; + private int jid_folder; + + public ChangeZlecenieFolderSelectedListenerDedalActivity(int id_zlecenia, int jid_folder){ + this.id_zlecenia = id_zlecenia; + this.jid_folder = jid_folder; + } + + @Override + public void onItemSelected(AdapterView parent, View view, int pos, + long id) { + + Log.d(LOG, "ChangeZlecenieFolderSelectedListenerDedalActivity" ); + try { + int id_folder_gui = folderIds.get(pos); + + // jeśli id_folder z gui jest taki sam jak w json to nie ma sensu wysyłać + Log.d("my_debug", "jid_folder: "+jid_folder+", id_folder_gui: "+id_folder_gui); + if( jid_folder == id_folder_gui ) { + return; + } + + setIdFolderInListaProfil(id_zlecenia, id_folder_gui); + + JSONObject mainJs = new JSONObject(); + JSONObject contentJs = new JSONObject(); + contentJs.put("id_zlecenia", id_zlecenia); + contentJs.put("id_folder", id_folder_gui); + mainJs.put("zlecenie", contentJs); + + Date d = new Date(); + String genName = "folder_"+d.getTime() + ".mod"; + File dstDir = new File(prefs.getString("dir", "") + "/upload_folders_mod"); + if( !dstDir.isDirectory()){ dstDir.mkdirs(); } + + DedalHelper.putFileContent(prefs.getString("dir", "") + "/upload_folders_mod/" + genName, mainJs.toString()); + + //todo: dkuz: po co to? + // wystartuj/obudz serwis +// Context context = getApplicationContext(); +// Intent service = new Intent(context, DedalService.class); +// context.startService(service); + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + protected void setIdFolderInListaProfil(int id_zlecenia, + int id_folder) { + try { + File dLista = new File(prefs.getString("dir", "") + "/baza/lista.profil"); + if( dLista.isFile()){ + String s = DedalHelper.getFileContent(dLista.getAbsolutePath()); + JSONObject jFile = new JSONObject(s); + + JSONObject jProfiles = jFile.getJSONObject("profile"); + Iterator pKeys = jProfiles.keys(); + //Boolean break_ = false; + + while( pKeys.hasNext()){ + String idProfilu = (String)pKeys.next(); + JSONObject jProfil = jProfiles.getJSONObject(idProfilu); + JSONObject jZlecenia = jProfil.getJSONObject("zlecenia"); + Iterator pKeys2 = jZlecenia.keys(); + while( pKeys2.hasNext() ){ + String id_zlecenia_curr = (String)pKeys2.next(); + if ( id_zlecenia_curr.equals( Integer.toString(id_zlecenia) ) ) { + JSONObject jZlecenie = jZlecenia.getJSONObject(Integer.toString(id_zlecenia)); + if(id_folder == 0) { + jZlecenie.put("id_folder", "null"); + } + else { + jZlecenie.put("id_folder", id_folder); + } + } + else { + continue; + } + } +// if( break_ ) { +// break; +// } + } + DedalHelper.putFileContent(prefs.getString("dir", "") + "/baza/lista.profil", jFile.toString()); + } + + + + } catch (JSONException e) { + e.printStackTrace(); + } + + } + + @Override + public void onNothingSelected(AdapterView arg0) { + // TODO Auto-generated method stub + + } + + } + +// private class PhotoUploadResponseHandler implements ResponseHandler { +// +// @Override +// public Object handleResponse(HttpResponse response) +// throws ClientProtocolException, IOException { +// +// HttpEntity r_entity = response.getEntity(); +// String responseString = EntityUtils.toString(r_entity); +// Log.d("UPLOAD", responseString); +// +// return null; +// } +// +// } +// + +// String readFile(InputStream in) throws IOException { +// StringBuffer sb = new StringBuffer(); +// byte buffer[] = new byte[1000]; +// int s = 0; +// while ((s = in.read(buffer)) > 0) { +// String st =new String(buffer, 0, s); +// sb.append(st); +// } +// return sb.toString(); +// } + + + + protected void find_powtarzalne(JSONObject jo, Integer id_pow) { + try { + if (jo.has(STRUCT_POWTARZALNY) && jo.getString(STRUCT_POWTARZALNY).equals("tak") && !jo.has("usun")) { + HashMap temp = new HashMap(); + temp.put(jo.getInt("id_wiersz_szablonu"), jo.getInt("id")); + + ostatni_powtarzalny.put(jo.getInt("parent"), temp); + + HashMap temp2 = new HashMap(); + if (ilosc_powtarzalnych.get(jo.getInt("parent")) != null && ilosc_powtarzalnych.get(jo.getInt("parent")).get(jo.getInt("id_wiersz_szablonu")) != null) { + Integer ilosc = ilosc_powtarzalnych.get(jo.getInt("parent")).get(jo.getInt("id_wiersz_szablonu")); + + temp2.put(jo.getInt("id_wiersz_szablonu"), ilosc + 1); + ilosc_powtarzalnych.put(jo.getInt("parent"), temp2); + } else { + temp2.put(jo.getInt("id_wiersz_szablonu"), 1); + ilosc_powtarzalnych.put(jo.getInt("parent"), temp2); + } + + id_pow = jo.getInt("id"); + } + + if (jo.has(STRUCT_TYP_DANYCH) && jo.getString(STRUCT_TYP_DANYCH).equals(TYPE_FOTO) && id_pow != 0) { + //Log.d("my_debug", "id_pow: "+id_pow); + elemntsWithFoto.put(id_pow, true); + } + + if (jo.has(STRUCT_KLIENT) && jo.getString(STRUCT_KLIENT).equals("accept")) { + //Log.d("my_debug", "klient: accept, id: "+ jo.getInt("id")); + if (ostatni_accept.get(jo.getInt("parent")) == null || ostatni_accept.get(jo.getInt("parent")).get(jo.getInt("id_wiersz_szablonu")) == null) { + HashMap temp3 = new HashMap(); + temp3.put(jo.getInt("id_wiersz_szablonu"), jo.getInt("id")); + ostatni_accept.put(jo.getInt("parent"), temp3); + } else { + if (ostatni_accept.get(jo.getInt("parent")).get(jo.getInt("id_wiersz_szablonu")) < jo.getInt("id")) { + HashMap temp3 = new HashMap(); + temp3.put(jo.getInt("id_wiersz_szablonu"), jo.getInt("id")); + ostatni_accept.put(jo.getInt("parent"), temp3); + } + } + } + + if (js.has("sub") && jo.has("id-orig")) { + //Log.d("my_debug", "no-sent"); + + //jo.put("no-sent", "true"); + + } + + JSONArray ja = jo.getJSONArray(STRUCT_CHILDS); + if (ja != null && ja.length() > 0) { + for (int i = 0; i < ja.length(); i++) { + find_powtarzalne(ja.getJSONObject(i), id_pow); + } + } + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + protected void sortujKolejnosc(ArrayList aM) { + Collections.sort(aM, new Comparator() { + @Override + public int compare(JSONObject lhs, JSONObject rhs) { + // TODO Auto-generated method stub + try { + if( lhs.getInt("kolejnosc") >(rhs.getInt("kolejnosc"))){ + return 1; + }else if( lhs.getInt("kolejnosc") < (rhs.getInt("kolejnosc"))){ + return -1; + }else{ + if( lhs.getInt("id") > (rhs.getInt("id"))) + return 1; + else if ( lhs.getInt("id") < (rhs.getInt("id"))) + return -1; + return 0; + } + } catch (JSONException e) { + // TODO Auto-generated catch block + //e.printStackTrace(); + } + return 0; + } + }); + } + +// private final class Change_focus implements OnFocusChangeListener { +// +// } + + /** + * Zapis zmian z elementów graficznych do struktury json. + * @param jo struktura do zapisu. + */ + protected void zapiszZmiany(JSONObject jo) { + // TODO Auto-generated method stub + + JSONArray ja; + //String komunikat = null; +// komunikat_obowiazkowe = ""; +// komunikat_walidacja = ""; + try { + if( !jo.has("id")){ + return; + } + + int id = jo.getInt("id"); + String typ_danych = jo.getString(STRUCT_TYP_DANYCH); + if(typ_danych.equals(TYPE_CHECK)){ + Object obj = DedalActivity.this.findViewById(id); + if( obj instanceof CheckBox) { + CheckBox cb = (CheckBox) DedalActivity.this.findViewById(id); + //ToggleButton cb = (ToggleButton) DedalActivity.this.findViewById(id); + if (cb != null) { //visible + if (cb.isChecked()) { + jo.put(STRUCT_WARTOSC, "on"); + } else { + jo.put(STRUCT_WARTOSC, "off"); + } + } + }else{ + if( obj!= null) { + Log.e("FORMATKA", "Błąd typu. id=" + id + " STRUCT_OPIS: " + jo.getString(STRUCT_OPIS)); + } + } + }else if( typ_danych.equals(TYPE_TEXT) || typ_danych.equals(TYPE_TEXTBOX)|| typ_danych.equals(TYPE_LICZBA)|| + typ_danych.equals(TYPE_KOLUMNA)|| typ_danych.equals(TYPE_DATA) || typ_danych.equals(TYPE_KWOTA)){ + View v = DedalActivity.this.findViewById(id); + if( v!= null){ //visible + if( !(v instanceof EditText)){ + Log.d("my_debug", "view nie jest EditText, id=" + id); + }else { + EditText et = (EditText) DedalActivity.this.findViewById(id); + jo.put(STRUCT_WARTOSC, et.getText().toString()); + + String opis = jo.getString(STRUCT_OPIS); + if (opis.trim().equals("")) { + opis = jo.getString("kod"); + } + + // walidacja pĂłl obowiazkowych + if (jo.has("obowiazkowe") && jo.getString("obowiazkowe").equals("tak")) { + if (et.getText().toString().trim().equals("") + && (et.isEnabled() || disableEditable.get(id) != null) + && et.getVisibility() == View.VISIBLE) { + + Log.d("my_debug", "obowiazkowe, " + opis); + komunikat_obowiazkowe += "-" + opis + "\n"; + } + } + + // walidacja poprawnoĹ›ci wpisanych danych + if (jo.has(STRUCT_WALIDACJA) && !jo.getString(STRUCT_WALIDACJA).trim().equals("")) { +// Log.d("my_debug", "et.isvisible: "+et.getVisibility()+", VISIBLE: "+View.VISIBLE); +// if(et.getVisibility() != View.VISIBLE) { +// Log.d("my_debug", "invisible !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); +// } + if (!et.getText().toString().trim().equals("") + && (et.isEnabled() || disableEditable.get(id) != null) + && et.getVisibility() == View.VISIBLE) { + + String wartosc_pola = et.getText().toString().trim(); + //String parts[] = + Log.d("my_debug", "waliduje, war: " + wartosc_pola + ", opis: " + opis); + String tabORs[] = jo.getString(STRUCT_WALIDACJA).trim().split("\\|\\|"); + String tabANDs[]; + String bLastOr = null; + String r; + Log.d("my_debug", "warunek: " + jo.getString(STRUCT_WALIDACJA).trim() + ", length: " + tabORs.length); + for (int or = 0; or < tabORs.length; or++) { + //alert(tabORs[or]); + //Log.d("my_debug", "tabors: or"+or+", war: "+tabORs[or]); + tabANDs = tabORs[or].split("\\&\\&"); + bLastOr = null; + for (int and = 0; and < tabANDs.length; and++) { + //Log.d("my_debug", "taband: and"+and+", war: "+tabANDs[and]); + r = null; + try { + r = check_walidacja(wartosc_pola, tabANDs[and].trim(), typ_danych, opis); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + if (r != null) { + bLastOr = r; + break; + } + } + if (bLastOr == null) { + break; + } + } + + //alert() + if (bLastOr != null) { + //return bLastOr; + komunikat_walidacja += bLastOr + "\n"; + } + } + } + } + + } + + }else if( typ_danych.equals(TYPE_RADIO)) { + View obj = DedalActivity.this.findViewById(id); + if (obj != null && obj instanceof RadioButton) { + RadioButton rb = (RadioButton) obj; + + if (rb != null)//visible + if (rb.isChecked()) { + jo.put(STRUCT_WARTOSC, "on"); + } else { + jo.put(STRUCT_WARTOSC, "off"); + } + } + + }else if( typ_danych.equals(TYPE_WYBOR)){ + View v = DedalActivity.this.findViewById(id); + if( v != null ) { + Spinner spin = (Spinner) DedalActivity.this.findViewById(id); + //Log.d("my_debug", "znalazďż˝em spinera, id: "+id+", wartosc: " + wyborSelected.get(id)); + + if( wyborSelected.get(id) != null) { + // walidacja pĂłl obowiazkowych + if (jo.has("obowiazkowe") && jo.getString("obowiazkowe").equals("tak")) { + if (wyborSelected.get(id) == 0 + && (spin.isEnabled() || disableEditable.get(id) != null) + && spin.getVisibility() == View.VISIBLE) { + + String opis = jo.getString(STRUCT_OPIS); + if (opis.trim().equals("")) { + opis = jo.getString("kod"); + } + + Log.d("my_debug", "obowiazkowe, " + opis); + komunikat_obowiazkowe += "-" + opis + "\n"; + } + } + jo.put(STRUCT_WARTOSC, wyborSelected.get(id)); + } + } + + }else if( typ_danych.equals(TYPE_RADIOLISTA)){ + + ja = jo.getJSONArray(STRUCT_CHILDS); + + Boolean is_checked = true; + Boolean is_visible = false; + if( ja!= null && ja.length()>0){ + int id_radio; + JSONObject jo_child; + RadioButton rb; + is_checked = false; + for ( int i=0; i < ja.length(); i++){ + jo_child = ja.getJSONObject(i); + id_radio = jo_child.getInt("id"); + //Log.d("my_debug", "id_radio: "+id_radio); + View obj = DedalActivity.this.findViewById(id_radio); + if(obj != null ) { + if( obj instanceof RadioButton ) { + rb = (RadioButton) obj; + if (rb != null) { //visible + if (rb.isEnabled()) { + if (rb.getVisibility() == View.VISIBLE) { + is_visible = true; + } + } + if (rb.isChecked()) { + is_checked = true; + jo.put(STRUCT_WARTOSC, ja.getJSONObject(i).getInt("id_wiersz_szablonu")); + break; + } + } + } + else { // przypadek gdzie mamy opcję: buttons. W tym wypadku wartość była zapisana już w jsonie podczas onclicka + Button bt = (Button) obj; + if( bt != null ) { + if (bt.isEnabled()) { + if (bt.getVisibility() == View.VISIBLE) { + is_visible = true; + } + } + if( jo.getString(STRUCT_WARTOSC).equals(jo_child.getString("id_wiersz_szablonu")) ) { + is_checked = true; + break; + } + } + } + } + } + } + // walidacja pďż˝l obowiazkowych + if ( jo.has("obowiazkowe") && jo.getString("obowiazkowe").equals("tak") ) { + int id_radiolista = jo.getInt("id"); + View radioLista = findViewById(id_radiolista); + //Log.d("my_debug", "wal radiolista: kod: "+jo.getString("kod")+", is_checked:"+is_checked+", is_visible: "+is_visible); //, radioLista.getVisibility(): "+radioLista.getVisibility()); + if( !is_checked && is_visible && radioLista.getVisibility() == View.VISIBLE) { + + String opis = jo.getString(STRUCT_OPIS); + if( opis.trim().equals("") ) { + opis = jo.getString("kod"); + } + Log.d("my_debug", "obowiazkowe, "+opis); + komunikat_obowiazkowe += "-"+opis + "\n"; + } + } + + //int id = jo.getInt("id"); + + // CHECKLISTA TUTAJ JEST POTRZEBNA DO WALIDACJE (DANE ZAPISYWANE Sďż˝ W IF(typ_danych.equals(TYPE_CHECK)) ) + }else if( typ_danych.equals(TYPE_CHECKLISTA)){ + + ja = jo.getJSONArray(STRUCT_CHILDS); + + Boolean is_checked = true; + Boolean is_visible = false; + if( ja!= null && ja.length()>0){ + int id_check; + CheckBox ch; + is_checked = false; + for ( int i=0; i0){ + for ( int i=0; i m = new ArrayList(); + String pattern = "PRE_TODAY([\\-,\\+])([\\d])"; + Matcher matcher = Pattern.compile(pattern).matcher(granica_pola); + if( matcher.matches() ) { + String sign = matcher.group(1); + String days = matcher.group(2); + Log.d("my_debug", "sign: "+sign+", days: "+days); + //String dt = "2008-01-01"; // Start date + DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar c = Calendar.getInstance(); + //c.setTime(); + int days_int = 0; + if( "-".equals(sign) ) { + days_int = Integer.parseInt(days)*(-1); + } + else if( "+".equals(sign) ) { + days_int = Integer.parseInt(days); + } + + c.add(Calendar.DATE, days_int); // number of days to add + granica_pola = dateFormat.format(c.getTime()); // dt is now the new date); + } + + //szukanie PRE_TODAY bez działaia matematycznego + if( granica_pola.length() > 4 && granica_pola.equals("PRE_TODAY") ) { + DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar c = Calendar.getInstance(); + granica_pola = dateFormat.format(c.getTime()); + + } + // jeĹ›li jest PRE_ to znaczy ĹĽe naleĹĽy odczytać id pola wzglÄ™dem ktĂłrego trzeba walidować i odczytać jego wartość bÄ™dÄ…cÄ… granicÄ… + else if( granica_pola.length() > 4 && granica_pola.substring(0,4).equals("PRE_") ) { + + //Log.d("my_debug", "wykryto PRE_"); + String id_pola_granicy_str = granica_pola.substring(4, granica_pola.length()); + try { + int id_pola_granicy_int = Integer.parseInt(id_pola_granicy_str); + View v = DedalActivity.this.findViewById(id_pola_granicy_int); + if( v != null ) { + EditText et = (EditText)DedalActivity.this.findViewById(id_pola_granicy_int); + granica_pola = et.getText().toString(); + } + }catch(NumberFormatException nfe) { + Log.d("my_debug", "id_pola_granicy_str: "+id_pola_granicy_str+" nie jest int"); + return null; + } + //Log.d("my_debug", "koniec PRE_, granica_pola: "+granica_pola); + } + + String wartosc = wartosc_pola.trim(); + String granica = granica_pola.trim(); + Log.d("my_debug", "oper: "+oper+", war: "+wartosc_pola+", gran: "+granica_pola); + Double wartoscNum = 0.0; + Double granicaNum = 0.0; + + String endl = "\n"; + + if( typ_danych.equals(TYPE_DATA) ) { + String walid_date_wartosc[] = wartosc.split("-"); + String walid_date_granica[] = granica.split("-"); + if ( !isGranicaIsDay(granica) && !granica.equals("HOLIDAY") ) { + if( walid_date_wartosc.length < 3 || walid_date_granica.length < 3 ) { // to nie jest data + Log.d("my_debug", "wartoĹ›ci nie sÄ… datami"); + return null; + } + } + + String check_wartosc[] = wartosc.split("\\s+"); + String check_granica[] = granica.split("\\s+"); + + if ( check_wartosc.length < 2 || check_wartosc[1] != null ) { // nie istnieje godzina w wartoďż˝ci to usuďż˝ godzinďż˝ z granicy + granica = check_granica[0]; + } + if ( check_granica.length < 2 || check_granica[1] != null ) { // nie istnieje godzina w granicy to usuďż˝ godzinďż˝ z wartoďż˝ci + wartosc = check_wartosc[0]; + } + + // Sprawdzanie dni tygodnia + if( oper.equals("df") && isGranicaIsDay(granica) ) { + Log.d("my_debug", "sprawdzam dzieĹ„ tygodnia: "); + Boolean ch = check_week_day(check_wartosc[0], granica); + if( ch ) { + komunikat="- "+opis_pola; + komunikat=komunikat+" - "+res.getString(R.string.dzien_tygodnia_daty)+" ("+wartosc_pola+") "+res.getString(R.string.musi_byc_rozny)+" ("+granica+")" + endl; + return komunikat; + } + return null; + } + if( oper.equals("eq") && isGranicaIsDay(granica) ) { + Boolean ch = check_week_day(check_wartosc[0], granica); + if( !ch ) { + komunikat="- "+opis_pola; + komunikat=komunikat+" - "+res.getString(R.string.dzien_tygodnia_daty)+" ("+wartosc_pola+") "+res.getString(R.string.musi_byc)+" ("+granica+")" + endl; + return komunikat; + } + return null; + } + //// + + // sprawdzanie Ĺ›wiÄ…t + if( oper.equals("df") && granica.equals("HOLIDAY") ) { + Boolean ch = check_holiday_day(check_wartosc[0]); // swieta - zmienna globalna (otrzymana z php) + if( ch ) { + komunikat="- "+opis_pola; + komunikat=komunikat+" - Wpisana data ("+wartosc_pola+") "+res.getString(R.string.nie_swieto) + endl; + return komunikat; + } + return null; + } + if( oper.equals("eq") && granica.equals("HOLIDAY") ) { + Boolean ch = check_holiday_day(check_wartosc[0]); // swieta - zmienna globalna (otrzymana z php) + if( !ch ) { + komunikat="- "+opis_pola; + komunikat=komunikat+" - Wpisana data ("+wartosc_pola+") "+res.getString(R.string.musi_swieto) + endl; + return komunikat; + } + return null; + } + + //do_walid = true; + } + else { + wartosc=wartosc.replace(',', '.'); + granica=granica.replace(',', '.'); + + try { + wartoscNum = Double.parseDouble(wartosc); + granicaNum = Double.parseDouble(granica); + }catch(NumberFormatException nfe) { + Log.d("my_debug", "wartoĹ›ci nie sÄ… liczbami"); + return null; + } + } + + + Log.d("my_debug", "num oper: "+oper+", war: "+wartoscNum+", gran: "+granicaNum); + Log.d("my_debug", "str oper: "+oper+", war: "+wartosc+", gran: "+granica); + + opis_pola = Html.fromHtml(opis_pola).toString(); + + if( oper.equals("ge") ) { + //if( ! (wartosc >= granica) ){ + // jeďż˝li data porďż˝wnaj stringi jeďż˝li nie porďż˝wnaj double + if ( (typ_danych.equals(TYPE_DATA) && !(wartosc.compareTo(granica) >= 0)) || + (!typ_danych.equals(TYPE_DATA) && !(wartoscNum >= granicaNum)) ) { + + komunikat="- "+opis_pola; + komunikat=komunikat+" - "+res.getString(R.string.wpisana_wartosc)+" ("+wartosc_pola+") "+res.getString(R.string.musi_wieksza_rowna)+" "+granica_pola+endl; + Log.d("my_debug", "wykryto ge"); + } + } + else if( oper.equals("gt") ) { + //if( ! (wartosc > granica )){ + // jeďż˝li data porďż˝wnaj stringi jeďż˝li nie porďż˝wnaj double + if ( (typ_danych.equals(TYPE_DATA) && !(wartosc.compareTo(granica) > 0)) || + (!typ_danych.equals(TYPE_DATA) && !(wartoscNum > granicaNum)) ) { + + komunikat="- "+opis_pola; + komunikat=komunikat+" - "+res.getString(R.string.wpisana_wartosc)+" ("+wartosc_pola+") "+res.getString(R.string.musi_wieksza)+" "+granica_pola+endl; + Log.d("my_debug", "wykryto gt"); + } + } + else if( oper.equals("le") ) { + //if( ! (wartosc <= granica )){ + // jeďż˝li data porďż˝wnaj stringi jeďż˝li nie porďż˝wnaj double + if ( (typ_danych.equals(TYPE_DATA) && !(wartosc.compareTo(granica) <= 0)) || + (!typ_danych.equals(TYPE_DATA) && !(wartoscNum <= granicaNum)) ) { + + komunikat="- "+opis_pola; + komunikat=komunikat+" - "+res.getString(R.string.wpisana_wartosc)+" ("+wartosc_pola+") "+res.getString(R.string.musi_mniejsza_rowna)+" "+granica_pola+endl; + Log.d("my_debug", "wykryto le"); + } + } + else if( oper.equals("ls") ) { + //if( ! (wartosc < granica )){ + // jeďż˝li data porďż˝wnaj stringi jeďż˝li nie porďż˝wnaj double + if ( (typ_danych.equals(TYPE_DATA) && !(wartosc.compareTo(granica) < 0)) || + (!typ_danych.equals(TYPE_DATA) && !(wartoscNum < granicaNum)) ) { + + komunikat="- "+opis_pola; + komunikat=komunikat+" - "+res.getString(R.string.wpisana_wartosc)+" ("+wartosc_pola+") "+res.getString(R.string.musi_mniejsza)+" "+granica_pola+endl; + Log.d("my_debug", "wykryto ls"); + } + } + else if( oper.equals("df") ) { + //if( wartosc == granica ){ + // jeďż˝li data porďż˝wnaj stringi jeďż˝li nie porďż˝wnaj double + if ( (typ_danych.equals(TYPE_DATA) && !(wartosc.compareTo(granica) == 0)) || + (!typ_danych.equals(TYPE_DATA) && !(wartoscNum == granicaNum)) ) { + + komunikat="- "+opis_pola; + komunikat=komunikat+" - "+res.getString(R.string.wpisana_wartosc)+" ("+wartosc_pola+") "+res.getString(R.string.musi_rozna)+" "+granica_pola+endl; + Log.d("my_debug", "wykryto df"); + } + } + else if( oper.equals("eq") ) { + //if( wartosc != granica ){ + // jeďż˝li data porďż˝wnaj stringi jeďż˝li nie porďż˝wnaj double + if ( (typ_danych.equals(TYPE_DATA) && !(wartosc.compareTo(granica) != 0)) || + (!typ_danych.equals(TYPE_DATA) && !(wartoscNum != granicaNum)) ) { + + komunikat="- "+opis_pola; + komunikat=komunikat+" - "+res.getString(R.string.wpisana_wartosc)+" ("+wartosc_pola+") "+res.getString(R.string.musi_rowna)+" "+granica_pola+endl; + Log.d("my_debug", "wykryto eq"); + } + } + else { + + } + //alert("default"); + + + return komunikat; + } + + protected boolean isGranicaIsDay(String granica) { + if( granica.equals("SUNDAY") || granica.equals("MONDAY") || granica.equals("TUESDAY") || granica.equals("WEDNESDAY") || granica.equals("THURSDAY") || granica.equals("FRIDAY") || granica.equals("SATURDAY") ) { + return true; + } + else { + return false; + } + } + + protected Boolean check_holiday_day(String date) { + // tutaj podajemy date w formacie: miesiÄ…c-dzieĹ„ (m-d) + Map swieta_stale = new HashMap(); + //tutaj podajemy date w formacie rok-miesiÄ…c-dzieĹ„ (Y-m-d) + Map swieta_ruchome = new HashMap(); + + swieta_stale.put("01-01", true); // nowy rok + swieta_stale.put("01-06", true); // trzech krĂłli + swieta_stale.put("05-01", true); // Ĺ›wiÄ™to pracy + swieta_stale.put("05-01", true); // konstytucja 3 maja + swieta_stale.put("08-15", true); // Ĺ›wiÄ™to wojska polskiego + swieta_stale.put("11-01", true); // wszystkich Ĺ›wiÄ™tych + swieta_stale.put("11-11", true); // Ĺ›wiÄ™to niepodlegĹ‚ośći + swieta_stale.put("12-25", true); // boĹĽe narodzenie + swieta_stale.put("12-26", true); // boĹĽe narodzenie + + // 2014 + swieta_ruchome.put("2014-04-20", true); // wielkanoc + swieta_ruchome.put("2014-04-21", true); // poniedziaĹ‚ek wielkanocny + swieta_ruchome.put("2014-05-08", true); // zielone Ĺ›wiÄ…tki + swieta_ruchome.put("2014-06-19", true); // boĹĽe ciaĹ‚o + + // 2015 + swieta_ruchome.put("2015-04-05", true); // wielkanoc + swieta_ruchome.put("2015-04-06", true); // poniedziaĹ‚ek wielkanocny + swieta_ruchome.put("2015-05-24", true); // zielone Ĺ›wiÄ…tki + swieta_ruchome.put("2015-06-04", true); // boĹĽe ciaĹ‚o + + date = date.trim(); + if( date.equals("") ) return false; + + String d[] = date.split("\\s+"); + date = d[0]; + + String date_split[] = date.split("-"); + if( date_split.length == 3 ) { // inaczej to nie jest data + String data_without_year = date_split[1]+"-"+date_split[2]; + if( swieta_stale.get(data_without_year) != null ) { + return true; + } + if( swieta_ruchome.get(date) != null ) { + return true; + } + } + + return false; + } + + protected Boolean check_week_day(String date, String wal_day_str) throws ParseException { + date = date.trim(); + if( date.equals("") ) return false; + + String d[] = date.split("\\s+"); + date = d[0]; + + //Date date_format = new Date(date); + + Calendar cal = Calendar.getInstance(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); + cal.setTime(sdf.parse(date));// all done + //Log.d("my_debug", "date, cal: "+cal.toString()); + + Boolean return_value = false; + + if ( wal_day_str.equals("SUNDAY") ) { + if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { + return_value = true; + } + } + if ( wal_day_str.equals("MONDAY") ) { + if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) { + return_value = true; + } + } + if ( wal_day_str.equals("TUESDAY") ) { + if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY) { + return_value = true; + } + } + if ( wal_day_str.equals("WEDNESDAY") ) { + if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY) { + return_value = true; + } + } + if ( wal_day_str.equals("THURSDAY") ) { + if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY) { + return_value = true; + } + } + if ( wal_day_str.equals("FRIDAY") ) { + if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) { + return_value = true; + } + } + if ( wal_day_str.equals("SATURDAY") ) { + if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { + return_value = true; + } + } + + return return_value; + + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.main, menu); + return true; + } + + protected void wyswietlPytanieCzyNastepneZdjecie(final String folder) { + // TODO Auto-generated method stub + + AlertDialog.Builder alertDialog = new AlertDialog.Builder(DedalActivity.this); + alertDialog.setTitle( "Czy zrobić następne zdjęcie?" ); + // alertDialog.setMessage( "Wybierz opcję:" ); + alertDialog.setPositiveButton("TAK", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int which) { + + + Date d = new Date(); + String genName = "foto_"+d.getTime() + ".jpg"; +// File file = new File(getFilesDir().getAbsolutePath() + "/mDedal/"+m_id+"/"+folder + "/" +genName); + File file = new File(prefs.getString("dir", "")+ "/mDedalCam/" +genName); + Uri oFU = Uri.fromFile(file); + StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); + StrictMode.setVmPolicy(builder.build()); + Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE); //moďż˝e secure? + intent.putExtra(MediaStore.EXTRA_OUTPUT, oFU); + + // foto_kod = folder; + foto_name = genName; + dialog.dismiss(); + startActivityForResult(intent, TAKE_PICTURE); + } + }); + + alertDialog.setNegativeButton("Zakończ robienie zdjęć.", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int which) { + //mod_json_files(false); + dialog.dismiss(); + DedalActivity.this.reload(); + } + }); + alertDialog.show(); + + } + + + @Override + protected void onDestroy() { + // TODO Auto-generated method stub + super.onDestroy(); + + radioParentsIds.clear(); + radiogroups.clear(); + + radioJson.clear(); + checkJson.clear(); + groupContainer.clear(); + + wyborSelected.clear(); + items_id.clear(); + + ostatni_powtarzalny.clear(); + ostatni_accept.clear(); + ilosc_powtarzalnych.clear(); + tabela_ostatni_wiersz.clear(); + elemntsWithFoto.clear(); + disableEditable.clear(); + + elemntsEnable.clear(); + + radioParentsIds = null; + radiogroups = null; + + radioJson = null; + checkJson = null;; + groupContainer = null; + + wyborSelected = null; + items_id = null; + + ostatni_powtarzalny = null; + ostatni_accept = null; + tabela_ostatni_wiersz = null; + elemntsWithFoto = null; + disableEditable = null; + + params = null; + js = null; + + dluznikItems_names = null; + dluznikItems_id_dluznik = null; + //selectedDluznikPerInterwencja = null; + + + folderIds = null; + folderNazwy = null; + + pola_tabela.clear(); + supportOnLoadReferences = null; + + + ListActivity.onDestroyD(this); + } + + protected boolean IsInteger(String str) + { + try + { + Integer.parseInt(str); + return true; + } + catch(NumberFormatException nfe) + { + return false; + } + } + + private class MyOnItemSelectedListener implements OnItemSelectedListener { + // private final JSONObject jo; + + String id_interwencji = null; + boolean first_selection = true; + + public MyOnItemSelectedListener(String id_interwencji) { + this.id_interwencji = id_interwencji; + } + + @Override + public void onItemSelected(AdapterView parent, View view, int pos, long id) { + Log.d("my_debug", "spinner, dluznik id: " + dluznikItems_id_dluznik.get(pos) + ", dluznik name: " + dluznikItems_names.get(pos)); + try { + JSONObject jo = find_element_from_Array(js, this.id_interwencji); + String id_dluznika = dluznikItems_id_dluznik.get(pos); + jo.put("id_dluznika", id_dluznika); + + if( selectedDluznikPerInterwencja == null ) { + selectedDluznikPerInterwencja = new HashMap(); + } + selectedDluznikPerInterwencja.put(this.id_interwencji, id_dluznika); + + if( !first_selection ) { + setModified(); + } + else { + first_selection = false; + } + //Log.d("my_debug", "jo: "+jo.toString()); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + @Override + public void onNothingSelected(AdapterView arg0) { + } + } + + protected void supporRadioRef(JSONObject radio_ref_jo, int visibility) { + Opcje op_ref = new Opcje(radio_ref_jo); + String opcja_ref = op_ref.get_opcje("referencja"); + String split[] = opcja_ref.split(","); + String ref_code = split[0]; + String ancestor_code = null; + int ancestor_id = 0; + + if( split.length > 1 ) { + ancestor_code = split[1]; + } + ancestor_id = getMyAcceptId(radio_ref_jo, ancestor_code); + + Log.d("my_debug", "ancestor_id: "+ancestor_id); + if( ancestor_id >= 0 ) { + JSONObject jo_ref = findElementByCodeAndAncestor(ref_code, Integer.toString(ancestor_id)); + if (jo_ref != null) { + try { + int id_ref = jo_ref.getInt("id"); + View view_ref = findViewById(id_ref); + + if (view_ref != null) { + + ViewGroup view_parent = (ViewGroup) view_ref.getParent(); + + view_parent.setVisibility(visibility); + setVisibilityForAllChildren(jo_ref, visibility); +// if ( op.check_opcje("referencja") ) { +// view_parent.setVisibility(View.VISIBLE); +// setVisibilityForAllChildren(jo_ref, View.VISIBLE); +// Log.d("my_debug", "referencja, set visible"); +// } +// else { +// view_parent.setVisibility(View.GONE); +// setVisibilityForAllChildren(jo_ref, View.GONE); +// Log.d("my_debug", "referencja, set invisible"); +// } + } + + //wyswietlPole(subView, jo_ref, true, view.isEnabled(), status_interwencji_temp); + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + } + + private void setVisibilityForAllChildren(JSONObject jo, int visible) { + if( jo.has("id") ) { + try { + int id = jo.getInt("id"); + View view = findViewById(id); + if( view != null ) { + view.setVisibility(visible); + } + } catch (JSONException e) { + e.printStackTrace(); + } + + } + try { + if( jo.has(STRUCT_CHILDS) && jo.getJSONArray(STRUCT_CHILDS).length() > 0 ) { + JSONArray childsJ = jo.getJSONArray(STRUCT_CHILDS); + for( int i = 0 ; i < childsJ.length() ; i++ ) { + JSONObject childJ = childsJ.getJSONObject(i); + setVisibilityForAllChildren(childJ, visible); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + + private class RadioOnClickListener implements OnClickListener { + + JSONObject radio_ref_jo = null; + + public RadioOnClickListener(JSONObject radio_ref_jo) { + this.radio_ref_jo = radio_ref_jo; + } + + @Override + public void onClick(View v) { + //v.getParent().ge + + + y = sw.getScrollY(); + Integer nGr = radioParentsIds.get(v.getId()); + List list = radiogroups.get(nGr); + + //setModified(); + if( v instanceof RadioButton) { + setModified(); + } + + JSONObject jo = find_element_from_Array(js, ""+v.getId()); + for( int i=0; i 0) { + for (int j = 0; j < ja2.length(); j++) { + try { + // Log.d("my_debug", "b.isEnabled: "+(b.isEnabled())); + wyswietlPole(subView, ja2.getJSONObject(j), true, view.isEnabled(), status_interwencji_temp); + + // wyswietlPole(subView, ja2.getJSONObject(j), true, true); + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + + // jeśli jest referencja to pokaż/ukryj referencję + if( radio_ref_jo != null ) { + int visibility = 0; + if ( op.check_opcje("referencja") ) { + visibility = View.VISIBLE; + } + else { + visibility = View.GONE; + } + supporRadioRef(radio_ref_jo, visibility); + + + } + + //} + } + + } + } + sw.post(new Runnable() { + @Override + public void run() { + sw.scrollTo(0, y); + } + }); + } + } +} diff --git a/app/src/main/java/com/likesoft/mdedal/DedalDownloadService.java b/app/src/main/java/com/likesoft/mdedal/DedalDownloadService.java new file mode 100644 index 0000000..f3d67ff --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/DedalDownloadService.java @@ -0,0 +1,616 @@ +package com.likesoft.mdedal; + +import android.annotation.SuppressLint; +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.IBinder; +import android.preference.PreferenceManager; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Vector; + +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +//mport com.likesoft.mdedal.DedalDownloadService.WorkingThread; + +public class DedalDownloadService extends Service{ + + private static final String SRV = "DedalDownloadService"; + SharedPreferences prefs; + String hostPath = ""; + String login = "";//prefs.getString("user", ""); + String pass = "";//prefs.getString("password", ""); + String gzip = "true"; + + private static void trustAllHosts() { + + X509TrustManager easyTrustManager = new X509TrustManager() { + public void checkClientTrusted( + X509Certificate[] chain, + String authType) throws CertificateException { + // Oh, I am easy! + } + public void checkServerTrusted( + X509Certificate[] chain, + String authType) throws CertificateException { + Log.d("certyfikat", "Download -serverTrusted: " + Arrays.toString(chain)); + // Oh, I am easy! + } + public X509Certificate[] getAcceptedIssuers() { + return null; + } + + }; + + // Create a trust manager that does not validate certificate chains + TrustManager[] trustAllCerts = new TrustManager[] {easyTrustManager}; + + // Install the all-trusting trust manager + try { + SSLContext sc = SSLContext.getInstance("TLS"); + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + } catch (Exception e) { + Log.e(SRV, "", e); + } + } + + class WorkingDownloadThread implements Runnable { + + WorkingThread _wt; + public WorkingDownloadThread(WorkingThread wt) { + // TODO Auto-generated constructor stub + _wt = wt; + } + @Override + public void run() { + // TODO Auto-generated method stub + _wt.pobierzZleceniaPrio(); + File f=_wt.getNextFile() ; + while( f != null){ + Log.d(SRV, "Watek pobiera zlecenie: " + f.getName()); + _wt.pobierzZlecenie(f); + f=_wt.getNextFile() ; + } + } + } + + @SuppressLint("DefaultLocale") + class WorkingThread implements Runnable { + + public synchronized File getNextFile(){ + File f = null; + if( curPosition < files.length){ + f = files[curPosition]; + curPosition++; + } + return f; + } + + public void pobierzZleceniaPrio() { + File d_prio = new File(prefs.getString("dir", "") + "/queue_prio");//getApplicationContext().getFilesDir(); + if( d_prio.isDirectory() ) { + String sf_prio = d_prio.getAbsolutePath(); + Log.d(SRV,sf_prio); + File files_prio[] = d_prio.listFiles(); + + // pętla po priorytetowych (jeśli są) + for (int j = 0; j < files_prio.length; j++) { + + String id_zlecenia_prio = files_prio[j].getName(); + + try { + Log.d(SRV, "zacznam pobierac: " + id_zlecenia_prio); + loadToDisk(id_zlecenia_prio); + files_prio[j].delete(); + + } catch (MalformedURLException e) { + Log.e("DEDAL", "Niepoprawny URL", e); + } + } + } + } + + File files[]; + int curPosition = 0; + public final int threadsNo = 10; + Thread wdt[] = new Thread[threadsNo]; + @Override + public void run() { + Context context = getApplicationContext(); + prefs = PreferenceManager.getDefaultSharedPreferences(context); + hostPath = prefs.getString("hostName", ""); + login = prefs.getString("user", ""); + pass = DedalHelper.decodeB64(prefs.getString("password", "")); + File d = new File(prefs.getString("dir", "") + "/queue");//getApplicationContext().getFilesDir(); + String sf = d.getAbsolutePath(); + Log.d(SRV,sf); + files = d.listFiles(); + + + // odpal watki + Log.d(SRV, "Start watkow pobierajacych zlecenia"); + for( int i =0; i < threadsNo; i++){ + wdt[i] = new Thread(new WorkingDownloadThread( this)); + wdt[i].start(); + } + // czekaj na zakonczenie + for( int i =0; i < threadsNo; i++){ + try { + wdt[i].join(); + } catch (InterruptedException e) { + Log.e(SRV, "przerwano watek", e); + } + } + Log.d(SRV,"Sleep"); + } + + public void pobierzZlecenie(File curFile) { + String id_zlecenia = ""; + id_zlecenia = curFile.getName(); + + + // PRIORYTETOWE + pobierzZleceniaPrio(); + + // ZWYKŁE + try { + File f_queue = new File(prefs.getString("dir", "") + "/queue/"+id_zlecenia); + if( f_queue.exists() ) { + Log.d(SRV, "zacznam pobierac: " + id_zlecenia); + loadToDisk(id_zlecenia); + File d_prio = new File(prefs.getString("dir", "") + "/queue_prio");//getApplicationContext().getFilesDir(); + if( d_prio.isDirectory() ) { + File f_queue_prio = new File(prefs.getString("dir", "") + "/queue_prio/"+id_zlecenia); + if( f_queue_prio.exists() ) { + f_queue_prio.delete(); + } + } + curFile.delete(); + } + else { + Log.d(SRV, "plik: " + id_zlecenia + " nie istnieje w queue"); + } + + } catch (MalformedURLException e) { + Log.e("DEDAL", "Niepoprawny URL", e); + } + } + } + + void loadToDisk(String m_id) throws MalformedURLException { + + DedalHttpConnection con = new DedalHttpConnection(getApplicationContext()); + Map params_post = new HashMap(); + params_post.put("id_zlecenia", m_id); + params_post.put("gzip", gzip); + params_post.put("json", "true"); + + + String sPost = con.sendPost("xml/getZlecenieXml.php", params_post); + + + Log.d(SRV, "loadToDisk odczytany bufor, size: " + sPost.length()); + + File myFileMod = new File(prefs.getString("dir", "") + "/baza/"+m_id+".mod"); + if( myFileMod.exists()){ + myFileMod.delete(); + } + + DedalHelper.putFileContent(prefs.getString("dir", "") + "/baza/"+m_id+".json", sPost); + + // load fotos: + // 1. parse json + + // usun wpis z tego zlecenia w pliku pliki_kollekto/statuses.json + String statPath = prefs.getString("dir", "") + "/pliki_kollekto/statuses.json"; + String statJsString = readFileFromPath(statPath); + if( statJsString != null && !"".equals(statJsString) ) { + try { + JSONObject statJs = new JSONObject(statJsString); + if(statJs.has(m_id)) { + statJs.remove(m_id); + //writeFileToPath(statPath, statJs.toString()); + DedalHelper.putFileContent(statPath, statJs.toString()); + } + } catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + } + } + + try { + JSONObject js = new JSONObject(sPost); + + // 3. download files + JSONObject params = js.getJSONObject("param"); + if( params.has("status") && ( params.getString("status").equals("przydz_nie_odeb") || params.getString("status").equals("przydz_odeb") ) ){ + saveAttach(js, m_id); + Log.d("my_debug", "zapisuje pliki, zlecenie: "+m_id); + saveDokumentyKollekto(js, m_id); + } + + } catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + } + + + + + } + + void saveDokumentyKollekto ( JSONObject js, String m_id){ + JSONArray dokumenty_kollekto; + + File dir_pliki_kollekto = new File(prefs.getString("dir", "") + "/pliki_kollekto"); + //Log.d("my_debug", "saveDokumentyKollekto"); + if(!dir_pliki_kollekto.isDirectory()) { + //Log.d("my_debug", "tworze dir: pliki_kollekto"); + if (!dir_pliki_kollekto.mkdirs()) { + } + } + + try { + dokumenty_kollekto = js.getJSONArray("dokumenty_kollekto"); + JSONObject dokument; + String fileName; + String data_pobrania; + String url; + String path; + for ( int i=0; i(); + + + JSONArray jFiles = jo.getJSONArray("files"); + if( jFiles != null && jFiles.length()>0){ + for( int i=0; i0){ + for( int i=0; i0){ + for ( int i=0; i 0) { + String st =new String(buffer, 0, s); + //Log.d(SRV, "i=" + s +", data:" + st); + sb.append(st); + } + return sb.toString(); + } + + + public String readFileFromPath(String path) { + + String content = ""; + File myFile = new File(path); + if( myFile.isFile()){ + content = DedalHelper.getFileContent(myFile.getAbsolutePath()); + } + return content; + } + + @Override + public IBinder onBind(Intent arg0) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/app/src/main/java/com/likesoft/mdedal/DedalHelper.java b/app/src/main/java/com/likesoft/mdedal/DedalHelper.java new file mode 100644 index 0000000..080bad9 --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/DedalHelper.java @@ -0,0 +1,538 @@ +package com.likesoft.mdedal; + +import android.content.SharedPreferences; +import android.os.Environment; +import android.preference.PreferenceManager; +import android.util.Base64; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.security.Key; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.SecretKeySpec; + +public class DedalHelper { + + + static HashMap statusy; + static { + statusy = new HashMap(); + statusy.put("wypelniane", "WYPE�NIANE"); + statusy.put("nie_przydz", "NIEPRZYDZIELONE"); + statusy.put("przydz_nie_odeb", "PRZYDZIELONE"); + statusy.put("przydz_odeb", "REALIZACJA"); + statusy.put("wykonane", "WYKONANE"); + statusy.put("wykonane_zaak", "ZAAKCEPTOWANE"); + statusy.put("odrzucone", "ODRZUCONE"); + statusy.put("anulowane", "ANULOWANE"); + statusy.put("anulowane_zaak", "ANULOWANE_ZAAKCEPTOWANE"); + statusy.put("zawieszona", "ZAWIESZONA"); + } +// static DedalHelper obj = new DedalHelper(); +// public DedalHelper(){ +// } + public static String getStatusDesc( String s){ + if( statusy.containsKey(s)){ + return statusy.get(s); + }else{ + return s; + } + } + + // +// static HashMap sts; +// static { +// sts = new HashMap(); +// sts.put("wypelniane", "WYPE�NIANE"); +// sts.put("nie_przydz", "NIEPRZYDZIELONE"); +// sts.put("przydz_nie_odeb", "PRZYDZIELONE"); +// sts.put("przydz_odeb", "ODEBRANE"); +// sts.put("wykonane", "WYKONANE"); +// sts.put("wykonane_zaak", "ZAAKCEPTOWANE"); +// sts.put("odrzucone", "ODRZUCONE"); +// sts.put("anulowane", "ANULOWANE"); +// sts.put("anulowane_zaak", "ANULOWANE_ZAAKCEPTOWANE"); +// sts.put("zawieszona", "ZAWIESZONA"); +// } +// public static String getStatusDescShort( String s){ +// if( statusy.containsKey(s)){ +// return statusy.get(s); +// }else{ +// return s; +// } +// } + // Input a double latitude or longitude in the decimal format + // e.g. -79.982195 + public static String decimalToDMS(double coord) { + String output, degrees, minutes, seconds; + + // gets the modulus the coordinate divided by one (MOD1). + // in other words gets all the numbers after the decimal point. + // e.g. mod := -79.982195 % 1 == 0.982195 + // + // next get the integer part of the coord. On other words the whole number part. + // e.g. intPart := -79 + + double mod = coord % 1; + int intPart = (int)coord; + + //set degrees to the value of intPart + //e.g. degrees := "-79" + + degrees = String.valueOf(intPart); + + // next times the MOD1 of degrees by 60 so we can find the integer part for minutes. + // get the MOD1 of the new coord to find the numbers after the decimal point. + // e.g. coord := 0.982195 * 60 == 58.9317 + // mod := 58.9317 % 1 == 0.9317 + // + // next get the value of the integer part of the coord. + // e.g. intPart := 58 + + coord = mod * 60; + mod = coord % 1; + intPart = (int)coord; + if (intPart < 0) { + // Convert number to positive if it's negative. + intPart *= -1; + } + + // set minutes to the value of intPart. + // e.g. minutes = "58" + minutes = String.valueOf(intPart); + + //do the same again for minutes + //e.g. coord := 0.9317 * 60 == 55.902 + //e.g. intPart := 55 + coord = mod * 60; + intPart = (int)coord; + if (intPart < 0) { + // Convert number to positive if it's negative. + intPart *= -1; + } + + // set seconds to the value of intPart. + // e.g. seconds = "55" + seconds = String.valueOf(intPart); + + // I used this format for android but you can change it + // to return in whatever format you like + // e.g. output = "-79/1,58/1,56/1" + output = degrees + "/1," + minutes + "/1," + seconds + "/1"; + + //Standard output of D°M′S″ + //output = degrees + "°" + minutes + "'" + seconds + "\""; + + return output; + } + /* + * Conversion DMS to decimal + * + * Input: latitude or longitude in the DMS format ( example: W 79° 58' 55.903") + * Return: latitude or longitude in decimal format + * hemisphereOUmeridien => {W,E,S,N} + * + */ + public static double DMSToDecimal(String hemisphereOUmeridien,double degres,double minutes,double secondes) + { + double LatOrLon=0; + double signe=1.0; + + if((hemisphereOUmeridien.equals("W"))||(hemisphereOUmeridien.equals("S"))) {signe=-1.0;} + LatOrLon = signe*(Math.floor(degres) + Math.floor(minutes)/60.0 + secondes/3600.0); + + return(LatOrLon); + } + + public static String getValueFromKod(String kod, JSONObject jZlecenie) { + String value = ""; + try{ + if( kod.equals("tworca")){ + value = jZlecenie.getString("tworca_login");//id_tworca + }else if( kod.equals("inspektor")){ + //Log.d("Helper", "kod,") + value = jZlecenie.getString("inspektor_login"); + }else if( kod.equals("info_alert")){ + value = jZlecenie.getString("data_alert"); + }else if( kod.equals("nr_sprawy-link")){ + value = jZlecenie.getString("nr_sprawy"); + }else if( kod.equals("status")){ + value = DedalHelper.getStatusDesc(jZlecenie.getString("status")); + //tw.setText(DedalHelper.getStatusDescShort(jZlecenie.getString("status"))); +// }else if( kod.equals("")){ + }else if( kod.startsWith("data_")){ + String s = jZlecenie.getString(kod); + if( s.length()>=10){ + value = jZlecenie.getString(kod).substring(0, 10); + }else{ + value = s; + } + }else{ + if( !jZlecenie.isNull(kod)){ + value = jZlecenie.getString(kod); + } + } + }catch( JSONException jE){ + Log.d("ListActivity", jE.getMessage()); + } + + + + return value; + } + + public static String getCurrentDate() { + return getCurrentDate("yyyy-MM-dd HH:mm:ss"); + } + + public static String getCurrentDate(String format) { + DateFormat dateFormat = new SimpleDateFormat(format); + Calendar c = Calendar.getInstance(); + return dateFormat.format(c.getTime()); + } + public static String getFileContent(String file_path) { + return getCryptFileContent(file_path); + } + + public static boolean putFileContent(String file_path, String content) { + return putCryptFileContent(file_path, content); + } +/* + public static String getFileContentSimple(String file_path) { + String return_str = ""; + + File ffile = new File(file_path); + if( !ffile.exists() ) { + return return_str; + } + + int length = (int) ffile.length(); + byte[] bytes = new byte[length]; + + FileInputStream in = null; + try { + in = new FileInputStream(ffile); + try { + in.read(bytes); + } finally { + in.close(); + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + return_str = new String(bytes); + return return_str; + } */ + + public static byte [] key; + + public static byte[] generateKey() throws Exception + { + if( key != null){ + return key; + } + byte[] keyStart = "likesoft".getBytes("UTF-8"); + + String pass = "HasloD0Maga7nu"; + + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + File f = new File(Environment.getExternalStorageDirectory()+ "/dedal/truststore.jks"); + if( f.isFile()) { + trustStore.load(new FileInputStream(f.getAbsolutePath()), pass.toCharArray()); + }else{ + trustStore.load(null, null); + } + + Key klucz = trustStore.getKey("dedal", pass.toCharArray()); + if( klucz!= null ){ + return klucz.getEncoded(); + }else { // zapisz do store nowy: + KeyGenerator kgen = KeyGenerator.getInstance("AES"); + //SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").getProvider(); +// SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); + SecureRandom sr = new SecureRandom(); + sr.setSeed(keyStart); + kgen.init(128, sr); + SecretKey skey = kgen.generateKey(); + + trustStore.setKeyEntry("dedal", skey, pass.toCharArray(), null); + + FileOutputStream out = new FileOutputStream(f.getAbsolutePath()); + trustStore.store(out, pass.toCharArray()); + out.close(); + key = skey.getEncoded(); + } + return key; + } + + public static byte[] encodeFile( byte[] fileData) throws Exception + { + if( key == null){ + key = generateKey(); + } + + SecretKeySpec skeySpec = new SecretKeySpec(key, "AES"); + Cipher cipher = Cipher.getInstance("AES"); + cipher.init(Cipher.ENCRYPT_MODE, skeySpec); + byte[] encrypted = cipher.doFinal(fileData); + + return encrypted; + } + public static String encodeB64( String fileData) + { + try{ + byte[] e = encodeFile(fileData.getBytes()); + return Base64.encodeToString(e, Base64.DEFAULT); + }catch (Exception ex){ + Log.e("CRYPT", "decodeB64 problem"); + } + return fileData; + } + + public static byte[] decodeFile( byte[] fileData) throws Exception + { + if( key == null){ + key = generateKey(); + } + SecretKeySpec skeySpec = new SecretKeySpec(key, "AES"); + Cipher cipher = Cipher.getInstance("AES"); + cipher.init(Cipher.DECRYPT_MODE, skeySpec); + + try { + byte[] decrypted = cipher.doFinal(fileData); + return decrypted; + }catch( Exception e){ + Log.e("CRYPT", "nie udało się odszyfrować bytes ", e); + return fileData; + } + } +//Base64.decode(input, Base64.DEFAULT) + public static String decodeB64( String fileData) + { + try { + byte[] e = decodeFile(Base64.decode(fileData, Base64.DEFAULT)); + return new String(e); + }catch (Exception ex){ + Log.e("CRYPT", "decodeB64 problem"); + } + return fileData; + } + + public static void copyEncode(File src, File dst) throws IOException { + + if( !src.exists() ) { + return ; + } + + int length = (int) src.length(); + byte[] bytes = new byte[length]; + + + InputStream in = new FileInputStream(src); + OutputStream out = new FileOutputStream(dst); + + try { + in.read(bytes); + } finally { + in.close(); + } + + try { + byte[] coded = new byte[0]; + try { + coded = encodeFile(bytes); + } catch (Exception e) { + Log.e("CRYPT", "problem z kodowaniem", e); + } + out.write(coded); + } finally { + out.close(); + } + } + + public static String getCryptFileContent(String file_path) { + String return_str = ""; + + File ffile = new File(file_path); + if( !ffile.exists() ) { + return return_str; + } + + int length = (int) ffile.length(); + byte[] bytes = new byte[length]; + + FileInputStream in = null; + try { + in = new FileInputStream(ffile); + try { + in.read(bytes); + } finally { + in.close(); + } + } catch (FileNotFoundException e) { + Log.e("DEDAL", "File not found", e); + } catch (IOException e) { + Log.e("DEDAL", "IO", e); + } + + byte[] ret = new byte[0]; + try { + + ret = decodeFile(bytes); + return_str = new String(ret); + } catch (Exception e) { + Log.e("CRYPT", "nie udało się odszyfrować: " + file_path, e); + //jeśli nie udało sie odkodować, zwróć plik + return_str = new String(bytes); + } + + return return_str; + } + public static byte[] getCryptFileBytes(String file_path) { + + File ffile = new File(file_path); + if( !ffile.exists() ) { + return null; + } + + int length = (int) ffile.length(); + byte[] bytes = new byte[length]; + + FileInputStream in = null; + try { + in = new FileInputStream(ffile); + try { + in.read(bytes); + } finally { + in.close(); + } + } catch (FileNotFoundException e) { + Log.e("DEDAL", "File not found", e); + } catch (IOException e) { + Log.e("DEDAL", "IO", e); + } + + byte[] ret; + try { + + ret = decodeFile(bytes); + return ret; + } catch (Exception e) { + Log.e("CRYPT", "nie udało się odszyfrować: " + file_path, e); + //jeśli nie udało sie odkodować, zwróć plik + return bytes; + } + + } + + public static boolean putCryptFileContent(String file_path, String content) { + File ffile = new File(file_path); + + FileOutputStream stream = null; + try { + stream = new FileOutputStream(ffile); + try { + byte[] coded = encodeFile(content.getBytes()); + stream.write(coded); + } finally { + stream.close(); + return true; + } + } catch (FileNotFoundException e) { + Log.e("DEDAL", "File not found", e); + } catch (IOException e) { + Log.e("DedalHelper", "File can't be saved"+ file_path, e); +// System.exit(0); + } + return false; + } + +/* + public static boolean putFileContentSimple(String file_path, String content) { + File ffile = new File(file_path); + + FileOutputStream stream = null; + try { + stream = new FileOutputStream(ffile); + try { + stream.write(content.getBytes()); + } finally { + stream.close(); + return true; + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + Log.e("DedalHelper", "File can't be saved"+ file_path, e); + // getActivity().finish(); + System.exit(0); + } + + return false; + } +*/ + public static boolean deleteFile(String file_path) { + File file = new File(file_path); + if( file.exists() ) { + return file.delete(); + } + return false; + } + + public static String getModOrJsonFileName(String fileNameJson) { + String fileNameJson_mod = fileNameJson.replace(".json", ".mod"); + File file = new File(fileNameJson_mod); + if(file.exists()) { + return fileNameJson_mod; + } + return fileNameJson; + } + + public static String datetime2date(String datetime) { + String date = null; + try { + SimpleDateFormat sdf_date_time = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + SimpleDateFormat sdf_date = new SimpleDateFormat("yyyy-MM-dd"); + Date dat = sdf_date_time.parse(datetime); + date = sdf_date.format(dat); + } catch (ParseException e) { + Log.e("DEDAL", "Parse date", e); + } + return date; + } + +// public static int findInArrayList(ArrayList al, String content) { +// int j = -1; +// for( int i = 0 ; i < al.size() ; i++ ) { +// if( content.equals(al.get(i)) ) { +// j = i; +// break; +// } +// } +// return j; +// } +} diff --git a/app/src/main/java/com/likesoft/mdedal/DedalHttpConnection.java b/app/src/main/java/com/likesoft/mdedal/DedalHttpConnection.java new file mode 100644 index 0000000..fe7af6e --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/DedalHttpConnection.java @@ -0,0 +1,418 @@ +package com.likesoft.mdedal; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.security.KeyStore; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.net.ssl.HttpsURLConnection; + +import org.apache.http.Header; +import org.apache.http.HttpEntity; +import org.apache.http.HttpHost; +import org.apache.http.HttpRequest; +import org.apache.http.HttpResponse; +import org.apache.http.HttpVersion; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.PlainSocketFactory; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.scheme.SocketFactory; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; +import org.apache.http.message.BasicHeader; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpParams; +import org.apache.http.params.HttpProtocolParams; +import org.apache.http.protocol.HTTP; +import org.apache.http.protocol.HttpContext; +import org.apache.http.util.EntityUtils; + +import android.content.Context; +import android.content.SharedPreferences; +import android.preference.PreferenceManager; +import android.util.Base64; +import android.util.Log; + +public class DedalHttpConnection { + + private static final String SRV = "MyHttpConnection"; + private String login; + private String pass; + private String hostPath; + public static String certSerialNumber=""; + public static String certOdcisk=""; + private DefaultHttpClient mHttpClient; + public static Context context; + + public DedalHttpConnection(Context context) { + //hostPath = "http://192.168.1.106/svn_home/SmsGateServer/src"; + SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); + hostPath = sharedPrefs.getString("hostName", ""); + login = sharedPrefs.getString("user", ""); + pass = DedalHelper.decodeB64(sharedPrefs.getString("password", "")); + certSerialNumber = sharedPrefs.getString("certSerialNumber", ""); + + //String cert64 = Base64.decode(sharedPrefs.getString("certOdcisk")); + try { + certOdcisk = new String(DedalHelper.decodeFile(Base64.decode(sharedPrefs.getString("certOdcisk", ""), Base64.DEFAULT))); + } catch (Exception e) { + e.printStackTrace(); + } + + + Log.d("my_debug", "Create MyHttpConnection. hostPath: "+hostPath+", login: "+login); //+", pass: "+pass + this.context = context; + } + + public String sendPost(String scriptName) { + return sendPost(scriptName, null); + } + + public String sendPost(String scriptName, Map params) { + Log.d("my_debug", "sendPost, scriptName: "+scriptName+", params: "+params ); + + ServerCommunication(); + if( mHttpClient == null){ + Log.e("SECURITY", "Network not initialized"); + return null; + } + //Log.d("my_debug", "getSms"); + HttpPost httppost = new HttpPost( hostPath + "/" + scriptName); //sms_send_download.php"); +// + httppost.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded")); + httppost.setHeader(new BasicHeader("charset", "UTF-8")); +// +// + List parameters = new ArrayList(); + + parameters.add(new BasicNameValuePair("login", login)); + parameters.add(new BasicNameValuePair("pass", pass)); + + if( params != null ) { + Iterator iterator = params.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry mapEntry = (Map.Entry) iterator.next(); + String key = (String) mapEntry.getKey(); + String value = (String) mapEntry.getValue(); + //Log.d("my_debug", "The key is: " + key + ",value is :" + value); + parameters.add(new BasicNameValuePair(key, value)); + } + } + + + try { + httppost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8")); + HttpResponse response = mHttpClient.execute(httppost); + if( response != null){ + HttpEntity r_entity = response.getEntity(); + String responseString = EntityUtils.toString(r_entity); + Log.d("my_debug", "sendPost, response from "+scriptName+": "+responseString); + //httppost.completed(); + //response.body().close(); + mHttpClient.getConnectionManager().closeExpiredConnections(); + + int sC = response.getStatusLine().getStatusCode(); + + if( sC == 200 ) { + return responseString; + }else{ + String ctv = r_entity.getContentType().getValue(); + Log.d( "sendPost", "http code: " + sC + ", content type: " + ctv); + return null; + } + + } + } catch (UnsupportedEncodingException e) { + com.likesoft.mdedal.Log.e("DEDAL", "Encoding", e); + } catch (ClientProtocolException e) { + com.likesoft.mdedal.Log.e("DEDAL", "Client protocol", e); + } catch (IOException e) { + com.likesoft.mdedal.Log.e("DEDAL", "IO", e); + } + return null; + //Log.d(SRV, "Entity BasicNameValuePair za�adowane"); + + } + + public byte [] getBytePost(String scriptName, Map params) { + Log.d("my_debug", "sendPost, scriptName: "+scriptName+", params: "+params ); + ServerCommunication(); + if( mHttpClient == null){ + Log.e("SECURITY", "Network not initialized"); + return null; + } + + //Log.d("my_debug", "getSms"); + HttpPost httppost = new HttpPost( hostPath + "/" + scriptName); //sms_send_download.php"); +// + httppost.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded")); + httppost.setHeader(new BasicHeader("charset", "UTF-8")); +// +// + List parameters = new ArrayList(); + + parameters.add(new BasicNameValuePair("login", login)); + parameters.add(new BasicNameValuePair("pass", pass)); + + if( params != null ) { + Iterator iterator = params.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry mapEntry = (Map.Entry) iterator.next(); + String key = (String) mapEntry.getKey(); + String value = (String) mapEntry.getValue(); + //Log.d("my_debug", "The key is: " + key + ",value is :" + value); + parameters.add(new BasicNameValuePair(key, value)); + } + } + + + try { + httppost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8")); + HttpResponse response = mHttpClient.execute(httppost); + if( response != null){ + HttpEntity r_entity = response.getEntity(); + byte[] buffer = EntityUtils.toByteArray(r_entity); //new byte[in.available()]; + mHttpClient.getConnectionManager().shutdown(); + int sC = response.getStatusLine().getStatusCode(); + if( sC == 200 ) { + return buffer; + }else{ + String ctv = r_entity.getContentType().getValue(); + Log.d( "sendPost", "http code: " + sC + ", content type: " + ctv); + return null; + } + + } + } catch (UnsupportedEncodingException e) { + Log.e("getInputStream", "nieudane pobranie", e); + } catch (ClientProtocolException e) { + Log.e("getInputStream", "nieudane pobranie", e); + } catch (IOException e) { + Log.e("getInputStream", "nieudane pobranie", e); + } + return null; + + } + + + //image/jpeg Content type + public byte[] getPicture(String url) { + Log.d("my_debug", "getPicture, url: "+url); + ServerCommunication(); + if( mHttpClient == null){ + Log.e("SECURITY", "Network not initialized"); + return null; + } + + //Log.d("my_debug", "getSms"); + HttpPost httppost = new HttpPost( hostPath + "/" + url); //sms_send_download.php"); + httppost.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded")); + httppost.setHeader(new BasicHeader("charset", "UTF-8")); + List parameters = new ArrayList(); + parameters.add(new BasicNameValuePair("login", login)); + parameters.add(new BasicNameValuePair("pass", pass)); + + try { + httppost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8")); + HttpResponse response = mHttpClient.execute(httppost); + if( response != null){ + HttpEntity r_entity = response.getEntity(); + byte[] buffer = EntityUtils.toByteArray(r_entity); //new byte[in.available()]; + //response.getStatusLine(). + Header ct = r_entity.getContentType(); + String ctv = r_entity.getContentType().getValue(); + int sC = response.getStatusLine().getStatusCode(); + mHttpClient.getConnectionManager().shutdown(); + if( sC == 200 && ctv.toLowerCase().contains("jpg")) { + return buffer; + }else{ + Log.d( "GET_PICTURE", "http code: " + sC + ", content type: " + ctv); + return null; + } + + } + } catch (UnsupportedEncodingException e) { + com.likesoft.mdedal.Log.e("DEDAL", "Unsupported Encoding", e); + } catch (ClientProtocolException e) { + com.likesoft.mdedal.Log.e("DEDAL", "Client protocol", e); + } catch (IOException e) { + com.likesoft.mdedal.Log.e("DEDAL", "IO", e); + } + + + return null; + //Log.d(SRV, "Entity BasicNameValuePair za�adowane"); + + } +//todo: do poprawy - chyba nie działa pobieranie plików z Kollekto... + + /** + * @deprecated + * @param url + * @param path + * @param fileName + */ + void downloadFile (String url, String path, String fileName) { + + Log.d("my_debug", "downloadFile: url: "+url+" path: "+path+" fileName: "+fileName); + try { + + url = hostPath + "/" + url; + + File fId = new File(path); + if(!fId.isDirectory()) { + if (!fId.mkdirs()) { + } + } + + File myFile = new File(path+"/"+ fileName); + if( !myFile.exists()) { + myFile.createNewFile(); + + URL urlF = new URL(url+"/"+fileName); + + HttpURLConnection urlConnectionF; + if (urlF.getProtocol().toLowerCase().equals("https")) { + // trustAllHosts(); + HttpsURLConnection urlHttpsConnection = (HttpsURLConnection) urlF.openConnection(); + urlHttpsConnection.setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + urlConnectionF = urlHttpsConnection; + } else { + urlConnectionF = (HttpURLConnection) urlF.openConnection(); + } + + + InputStream inF = new BufferedInputStream(urlConnectionF.getInputStream()); + + FileOutputStream fosF; + + fosF = new FileOutputStream(myFile); + byte buffer[] = new byte[10000]; + int x = 0; + while( (x = inF.read(buffer)) >0){ + fosF.write(buffer, 0, x); + Log.d(SRV, "Picture - czytam znaków: " + x); + } + fosF.flush(); + fosF.close(); + } + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + Log.e(SRV, "", e); + } catch (IOException e) { + // TODO Auto-generated catch block + Log.e(SRV, "", e); + } + } + /* + private static void trustAllHosts() { + + X509TrustManager easyTrustManager = new X509TrustManager() { + public void checkClientTrusted( + X509Certificate[] chain, + String authType) throws CertificateException { + // Oh, I am easy! + } + public void checkServerTrusted( + X509Certificate[] chain, + String authType) throws CertificateException { + com.likesoft.mdedal.Log.d("certyfikat", "MyHttpConnection -serverTrusted23: " + Arrays.toString(chain)); + + + } + public X509Certificate[] getAcceptedIssuers() { + return null; + } + + }; + + // Create a trust manager that does not validate certificate chains + TrustManager[] trustAllCerts = new TrustManager[] {easyTrustManager}; + + // Install the all-trusting trust manager + try { +// SSLContext sc = SSLContext.getInstance("SSL"); + SSLContext sc = SSLContext.getInstance("TLS"); + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + + // +// SSLSocketFactory factory =sc.getSocketFactory(); +// SSLSocket socket =(SSLSocket)factory.createSocket("dedal.eos-ksi.pl", 443); +// socket.startHandshake(); +// SSLSession session = socket.getSession(); +// java.security.cert.Certificate[] servercerts = session.getPeerCertificates(); +// for (int i = 0; i < servercerts.length; i++) { +// System.out.print("-----BEGIN CERTIFICATE-----\n"); +// //System.out.print(Base64.encodeBytes().encode(servercerts[i].getEncoded())); +// // System.out.print(Base64.getEncoder().encode(servercerts[i].getEncoded())); +// byte[] e = servercerts[i].getEncoded(); +// System.out.print(Base64.encodeToString(e, 0)); +// System.out.print(servercerts[i].getEncoded()); +// System.out.print("\n-----END CERTIFICATE-----\n"); +// } +// socket.close(); + // + + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + } catch (Exception e) { + e.printStackTrace(); + Log.d("my_debug", ""); + } + } + */ + public static DefaultHttpClient getNewHttpClient() { + try { + // trustAllHosts(); + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + + org.apache.http.conn.ssl.SSLSocketFactory sf = new DedalSSLSocketFactory(trustStore); + if(BuildConfig.DEBUG) { + sf.setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + }else { + sf.setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); +// sf.setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); + } + + HttpParams params = new BasicHttpParams(); + HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); + HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); + + SchemeRegistry registry = new SchemeRegistry(); + + if(BuildConfig.DEBUG) { + registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + } + registry.register(new Scheme("https", (SocketFactory) sf, 443)); + + ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); + + return new DefaultHttpClient(ccm, params); + } catch (Exception e) { + Log.e("my_debug", "catch", e); + // return new DefaultHttpClient(); + return null; + } + } + + public void ServerCommunication() { + mHttpClient = DedalHttpConnection.getNewHttpClient(); + } +} diff --git a/app/src/main/java/com/likesoft/mdedal/DedalSSLSocketFactory.java b/app/src/main/java/com/likesoft/mdedal/DedalSSLSocketFactory.java new file mode 100644 index 0000000..6add1cb --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/DedalSSLSocketFactory.java @@ -0,0 +1,108 @@ +package com.likesoft.mdedal; + +import android.content.SharedPreferences; +import android.preference.PreferenceManager; +import android.util.Base64; + +import java.io.IOException; +import java.net.Socket; +import java.net.UnknownHostException; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +public class DedalSSLSocketFactory extends org.apache.http.conn.ssl.SSLSocketFactory { + SSLContext sslContext = SSLContext.getInstance("TLS"); + + public DedalSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { + super(truststore); + + TrustManager tm = new X509TrustManager() { + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + com.likesoft.mdedal.Log.d("certyfikat", "MySSLSocketFactory -checkClientTrusted: " + Arrays.toString(chain)); + } + + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + // com.likesoft.mdedal.Log.d("certyfikat", "MySSLSocketFactory -serverTrusted AA: " + Arrays.toString(chain)); + +// for (int i = 0; i < chain.length; i++) { +// // android.util.Log.d("cert Serial Number" + i + ":", chain[i].getSerialNumber().toString()); +// //Log.d( "cert", "validity: " + chain[0].checkValidity()); +// Collection> aN = chain[i].getSubjectAlternativeNames(); +// if( aN != null) { +// +// Object[] a = aN.toArray(); +// android.util.Log.d("cert AN", Arrays.toString(a)); +// } +// // Oh, I am easy! +// } + + if( chain.length>0){ + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(DedalHttpConnection.context); + if( DedalHttpConnection.certSerialNumber.length()==0) { //init + SharedPreferences.Editor e = prefs.edit(); + e.putString("certSerialNumber", chain[0].getSerialNumber().toString()); + e.commit(); + }else { //check + if( !chain[0].getSerialNumber().toString().equals(prefs.getString("certSerialNumber", "") )){ + // security problem + android.util.Log.e("SECURITY", "Cert Serial Number incorrect"); + throw new CertificateException("Cert Serial Number incorrect"); + } + } + + if( DedalHttpConnection.certSerialNumber.length()==0) { //init, gdy nie było jeszcze serial number + SharedPreferences.Editor e = prefs.edit(); + + byte[] sig; + try { + sig = DedalHelper. encodeFile(chain[0].getSignature()); + e.putString("certOdcisk", Base64.encodeToString(sig, Base64.DEFAULT)); + e.commit(); + } catch (Exception ex) { + android.util.Log.e("SECURITY", "Cert Signature encode incorrect"); + throw new CertificateException("Cert Signature incorrect"); + } + }else { //check + String chainSig = new String(chain[0].getSignature()); + + if( !chainSig.equals(DedalHttpConnection.certOdcisk )){ + // security problem + android.util.Log.e("SECURITY", "Cert Signature incorrect"); + throw new CertificateException("Cert Signature incorrect"); + } + } + + + } + } + + public X509Certificate[] getAcceptedIssuers() { + return null; + } + }; + + sslContext.init(null, new TrustManager[] { tm }, null); + } + + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { + return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); + } + + @Override + public Socket createSocket() throws IOException { + return sslContext.getSocketFactory().createSocket(); + } +} \ No newline at end of file diff --git a/app/src/main/java/com/likesoft/mdedal/DedalService.java b/app/src/main/java/com/likesoft/mdedal/DedalService.java new file mode 100644 index 0000000..c718b37 --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/DedalService.java @@ -0,0 +1,1680 @@ +package com.likesoft.mdedal; + +import android.Manifest; +import android.annotation.SuppressLint; +import android.app.Notification; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.SharedPreferences.Editor; +import android.content.pm.PackageManager; +import android.content.res.Resources; +import android.net.Uri; +import android.os.IBinder; +import android.os.Build; +import android.preference.PreferenceManager; +import androidx.core.content.ContextCompat; +import android.telephony.TelephonyManager; + +//import com.likesoft.mdedaltest.R; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.HttpVersion; +import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.PlainSocketFactory; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.scheme.SocketFactory; +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.entity.mime.content.ByteArrayBody; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; +import org.apache.http.message.BasicHeader; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpParams; +import org.apache.http.params.HttpProtocolParams; +import org.apache.http.protocol.HTTP; +import org.apache.http.util.EntityUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetAddress; +import java.net.MalformedURLException; +import java.net.URL; +import java.security.KeyStore; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.TreeSet; +import java.util.Vector; + +//import javax.net.ssl.SSLSocketFactory; +//import android.util.Log; + +public class DedalService extends Service { + + @SuppressLint({"MissingPermission", "HardwareIds"}) + private static String safeSubscriberId(Context ctx) { + try { + // Dostęp do IMSI tylko na API <= 28 (Pie) i z READ_PHONE_STATE + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P + && ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) { + TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE); + if (tm != null) { + return tm.getSimState() == TelephonyManager.SIM_STATE_READY ? tm.getSubscriberId() : ""; + } + } + } catch (Exception ignored) { } + return ""; + } + + private static String safeLine1Number(Context ctx) { + try { + boolean hasPermission = + ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_PHONE_NUMBERS) == PackageManager.PERMISSION_GRANTED + || ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED + || ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED; + if (hasPermission) { + TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE); + return tm != null ? tm.getLine1Number() : ""; + } + } catch (Exception ignored) { } + return ""; + } + + static Boolean isStopped = false; + private static final String SRV = "DedalService"; + SharedPreferences prefs; + String hostPath = ""; + String login = "";//prefs.getString("user", ""); + String pass = "";//prefs.getString("password", ""); + String gzip = "true"; +/* + private static void trustAllHosts() { + + X509TrustManager easyTrustManager = new X509TrustManager() { + public void checkClientTrusted( + X509Certificate[] chain, + String authType) throws CertificateException { + // Oh, I am easy! + } + + public void checkServerTrusted( + X509Certificate[] chain, + String authType) throws CertificateException { + Log.d("certyfikat", "DedalService serverTrusted: " + Arrays.toString(chain)); + // Oh, I am easy! + } + + public X509Certificate[] getAcceptedIssuers() { + return null; + } + + }; + + // Create a trust manager that does not validate certificate chains + TrustManager[] trustAllCerts = new TrustManager[]{easyTrustManager}; + + // Install the all-trusting trust manager + try { + SSLContext sc = SSLContext.getInstance("TLS"); + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + } catch (Exception e) { + e.printStackTrace(); + Log.e(SRV, "", e); + } + } +*/ + public static HttpClient getNewHttpClient() { + try { + //trustAllHosts(); + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + + org.apache.http.conn.ssl.SSLSocketFactory sf = new DedalSSLSocketFactory(trustStore); +// sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); + sf.setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + + HttpParams params = new BasicHttpParams(); + HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); + HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); + + SchemeRegistry registry = new SchemeRegistry(); + registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + registry.register(new Scheme("https", (SocketFactory) sf, 443)); + + ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); + + return new DefaultHttpClient(ccm, params); + } catch (Exception e) { + return new DefaultHttpClient(); + } + } + + + //Object w = new Object(); + @SuppressLint("DefaultLocale") + private class WorkingThread implements Runnable { + + @Override + public void run() { + //while( true){ + + Context context = getApplicationContext(); + prefs = PreferenceManager.getDefaultSharedPreferences(context); + hostPath = prefs.getString("hostName", ""); + login = prefs.getString("user", ""); + pass = DedalHelper.decodeB64(prefs.getString("password", "")); + + File fNext = new File(prefs.getString("dir", "") + "/dedalsrv.continue"); + if (fNext.exists()) { + fNext.delete(); + } + File fLock = new File(prefs.getString("dir", "") + "/dedalsrv.lock"); + try { + fLock.createNewFile(); + } catch (IOException e) { + Log.e(SRV, "", e); + } + File fconn = new File(prefs.getString("dir", "") + "/dedalsrv.connection"); + if (fconn.exists()) { + fconn.delete(); + } + + + //Your code goes here + File fLockLogin = new File(prefs.getString("dir", "") + "/dedalsrv.wrongLogin"); + Log.d(SRV, "Service upload check. "); + try { + if (!checkLoginConnection()) { + // zły login/haslo + if (!fLockLogin.exists()) { + fLockLogin.createNewFile(); + } + File fLockEnd = new File(prefs.getString("dir", "") + "/dedalsrv.lock"); + if (fLockEnd.exists()) { + fLockEnd.delete(); + } + return; + } else { + if (fLockLogin.exists()) { + fLockLogin.delete(); + } + } + + } catch (Exception cE) { + Log.e(SRV, "Problem połączenia." + cE.getMessage()); + Log.e(SRV, "", cE); + // błąd połączenia + File fLockEnd = new File(prefs.getString("dir", "") + "/dedalsrv.lock"); + if (fLockEnd.exists()) { + fLockEnd.delete(); + } + if (fLockLogin.exists()) { + fLockLogin.delete(); + } + + File fLockCon = new File(prefs.getString("dir", "") + "/dedalsrv.connection"); + try { + fLockCon.createNewFile(); + } catch (IOException econ) { + Log.e(SRV, "", econ); + } + + return; + } + + try { + + File fLockCon = new File(prefs.getString("dir", "") + "/dedalsrv.connection_password"); + if( fLockCon.exists()){ + fLockCon.delete(); + } + + uploadFiles(); + uploadModifications(); // przekazuje przez mobi.php, 5 nieudanych prób blokuje dostęp. + uploadFoldersModifications(); + uploadFoldersOrderModifications(); + uploadWidokProfilModifications(); + uploadKP(); + uploadKPWplaty(); + } catch (Exception cE) { + Log.e(SRV, "", cE); + } + try { + // tutaj pobierać pliki z serwera + checkNewIssues(); + + getKp(); + getKpWplaty(); + + } catch (Exception cE) { + Log.e(SRV, "", cE); + } + + File fLockEnd = new File(prefs.getString("dir", "") + "/dedalsrv.lock"); + if (fLockEnd.exists()) { + fLockEnd.delete(); + } + File fNextEnd = new File(prefs.getString("dir", "") + "/dedalsrv.continue"); + if (fNextEnd.exists()) { + fNextEnd.delete(); + } else { + int refreshPos = prefs.getInt("refresh", 2); + //android.R.id. + Resources res = getResources(); + int values[] = res.getIntArray(R.array.pref_sync_frequency_values); + res.getString(R.string.app_name); + + Log.d(SRV, "Sleep"); + +// int sleepTime =values[refreshPos]*1000; +// Log.d(SRV, "Sleep time: "+ sleepTime); +// Thread.sleep(sleepTime); //30sec=30000, 5min= 300000 + +// Alarm alarm = new Alarm(); +// alarm.CancelAlarm(context); +// alarm.SetAlarm(context); + + } + } + + public boolean PingVPN(URL url) { + try { + InetAddress address = InetAddress.getByName(url.getHost()); + + boolean reachable = address.isReachable(1000); + Log.d(SRV, "Is host reachable? " + reachable); + return reachable; + } catch (Exception e) { + Log.e("DEDAL", "PING VPN", e); + return false; + } + } + + private void setConnectionStatus( String status){ + File fStatus = new File(prefs.getString("dir", "") + "/dedal.status"); + try { + fStatus.createNewFile(); + //FileWriter(fStatus) + FileOutputStream fosStatus = new FileOutputStream(fStatus); + fosStatus.write(status.getBytes()); + fosStatus.flush(); + fosStatus.close(); + } catch (IOException e) { + Log.e(SRV, "", e); + } + } + private boolean checkLoginConnection() throws Exception { + // try { + Log.d(SRV, "checkLoginConnection"); + Context context = getApplicationContext(); + prefs = PreferenceManager.getDefaultSharedPreferences(context); + login = prefs.getString("user", ""); + pass = DedalHelper.decodeB64(prefs.getString("password", "")); + + // get GPS position + Double latitude = gps.getLatitude(); + Double longitude = gps.getLongitude(); + + + File fDir = new File(prefs.getString("dir", "") + "/baza"); + if (!fDir.isDirectory()) { + fDir.mkdirs(); + } + + + String imsistring = safeSubscriberId(getApplicationContext()); + if (imsistring == null || imsistring.isEmpty()) imsistring = "IMSI"; + String mPhoneNumber = safeLine1Number(getApplicationContext()); + if (mPhoneNumber == null || mPhoneNumber.isEmpty()) mPhoneNumber = "PHONE_LikeSoft"; + + String asUser; + asUser = prefs.getString("asuser", login); + + //co 0,5h wysyłać pełną listę zleceń. + URL url = null; + try { + url = new URL( + hostPath + "/xml/getListaZlecenJson2.php"); + + }catch (MalformedURLException mE){ + setConnectionStatus("NOT_AUTHORIZED"); + return false; + } + Log.d(SRV, url.toString()); + + //check server IP and ping. + if( !PingVPN(url)){ + //return false; + throw new Exception("VPN not working"); + } + + DedalHttpConnection con = new DedalHttpConnection(getApplicationContext()); + Map params_post = new HashMap(); + params_post.put("connection", "check"); + params_post.put("asuser", asUser); + params_post.put("gzip", gzip); + params_post.put("latitude", latitude.toString()); + params_post.put("longitude", longitude.toString()); + params_post.put("GPS", ""+gps.isGPSEnabled); + params_post.put("imsi", "&imsi="+imsistring+"T"+mPhoneNumber); + + //con.ServerCommunication(); + String s = con.sendPost("xml/getListaZlecenJson2.php", params_post); + + if( s!= null && s.length()>0 ) { + Log.d(SRV, "odczytany bufor, size: " + s.length()); + Log.d(SRV, "odczytany bufor: " + s); + // urlConnection.disconnect(); + + JSONObject jFile = new JSONObject(s); + String jStatus = jFile.getString("status"); + if ("NO_DATA".equals(jStatus)) { + setConnectionStatus("Brak danych"); + return true; // nothing to update + } else if ("NOT_ALLOWED".equals(jStatus)) { + setConnectionStatus("NOT_ALLOWED"); + return true; + } else if ("NOT_AUTHORIZED".equals(jStatus)) { + setConnectionStatus("NOT_AUTHORIZED"); + + return false; + } else if ("RELOAD".equals(jStatus)) { + // zaloguj za inspektora + //String asUser = prefs.getString("asUser", ""); + Log.d(SRV, "RELOAD:" + jFile.toString()); + String newPass = jFile.getString("asPassword"); + Editor e = prefs.edit(); + e.putString("user", asUser); + e.putString("password", DedalHelper.encodeB64(newPass)); + e.putString("asUser", ""); + e.commit(); + + context = getApplicationContext(); + prefs = PreferenceManager.getDefaultSharedPreferences(context); + login = prefs.getString("user", ""); + pass = DedalHelper.decodeB64(prefs.getString("password", "")); + + return checkLoginConnection(); + } else if ("OK".equals(jStatus)) { + setConnectionStatus(jFile.getString("valid_to")); + return true; + } + } +// } catch (Exception e) { +// +// Log.d(SRV, "problem"); +// } + return false; + } + + private void checkNewIssues( ) { +// try { + + TreeSet wczytaneZlecenia = new TreeSet(); + Log.d(SRV, "checkNewIssues"); + Context context = getApplicationContext(); + prefs = PreferenceManager.getDefaultSharedPreferences(context); + login = prefs.getString("user", ""); + pass = DedalHelper.decodeB64(prefs.getString("password", "")); + + + // get GPS position + Double latitude = gps.getLatitude(); + Double longitude = gps.getLongitude(); + + + + + //todo: remove issues not assigned to user. + Vector filesToDelete = new Vector(); + File d = new File(prefs.getString("dir", "") + "/baza");//getApplicationContext().getFilesDir(); + String sf = d.getAbsolutePath(); + Log.d(SRV,sf); + File files[] = d.listFiles(new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.toLowerCase().endsWith(".json") || name.toLowerCase().endsWith(".txt"); + } + }); + if( files != null) { + for (int i = 0; i < files.length; i++) { +// files[i].delete(); + filesToDelete.add(files[i].getName()); + //Log.d(SRV, "istnieje plik json: " + files[i].getName()); + } + } + + Map daty_modyfikacji_zlecen = wczytajDatyPoprzednichModyfikacji(); + + + try { + String imsistring = safeSubscriberId(getApplicationContext()); + if (imsistring == null || imsistring.isEmpty()) imsistring = "IMSI"; + String mPhoneNumber = safeLine1Number(getApplicationContext()); + if (mPhoneNumber == null || mPhoneNumber.isEmpty()) mPhoneNumber = "PHONE_LikeSoft"; + + String asUser; + asUser = prefs.getString("asuser", "");//login); + + DedalHttpConnection con = new DedalHttpConnection(getApplicationContext()); + Map params_post = new HashMap(); + params_post.put("asuser", asUser); + params_post.put("gzip", gzip); + params_post.put("latitude", latitude.toString()); + params_post.put("longitude", longitude.toString()); + params_post.put("GPS", ""+gps.isGPSEnabled); + params_post.put("imsi", "&imsi="+imsistring+"T"+mPhoneNumber); + + String s = con.sendPost("xml/getListaZlecenJson2.php", params_post); + + + Log.d(SRV, "odczytany bufor, size: " + s.length()); + DedalHelper.putFileContent(prefs.getString("dir", "") + "/baza/lista.profil.work", s); + + //Log.d(SRV, s); + JSONObject jFile = new JSONObject(s); + String jStatus = jFile.getString("status"); + if( "NO_DATA".equals(jStatus)){ + return; // nothing to update + }else if( "NOT_ALLOWED".equals(jStatus)){ + // remove all data + usunPliki(filesToDelete); + return; + }else if( "NOT_AUTHORIZED".equals(jStatus)){ + return; + }else if( "RELOAD".equals(jStatus)){ + // zaloguj za inspektora + return; + } + + JSONObject jProfiles = jFile.getJSONObject("profile"); + Iterator pKeys = jProfiles.keys(); + while( pKeys.hasNext()){ + String idProfilu = (String)pKeys.next(); + JSONObject jProfil = jProfiles.getJSONObject(idProfilu); + + JSONObject jZlecenia = null; + try{ + jZlecenia = jProfil.getJSONObject("zlecenia"); + }catch( JSONException jEx){ + // nie ma zleceń w tym profilu. + continue; + } + Log.d(SRV, "Odczytano zlecenia"); + Iterator keys = jZlecenia.keys(); + while( keys.hasNext()){ + String id = (String)keys.next(); + JSONObject jZlecenie = jZlecenia.getJSONObject(id); + + Log.d(SRV,"Zlecenie id:"+id);//+" JSON: " + jZlecenie.toString()); + + filesToDelete.remove(id+".json"); + filesToDelete.remove(id+".txt"); + + Boolean load = true; + File fId = new File(prefs.getString("dir", "") + "/baza/"+id+".json"); + if( fId.isFile()){ + Long lastMod=null;// = fId.lastModified(); + lastMod = daty_modyfikacji_zlecen.get(id); + //Date.parse(j.getString("data_zapisu")); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + try { + Date dZapis = sdf.parse(jZlecenie.getString("data_zapisu")); + long lastZapis = dZapis.getTime(); + if( lastMod != null && lastMod.longValue() >= lastZapis){ + load = false; +// Log.d(SRV, "Data zapisu jest mniejsza lub równa niż modyfikacja, plik: "+ fId.getName()); + }else{ + Log.d(SRV, "Data zapisu "+lastMod+" jest większa niż modyfikacja "+lastZapis+", nadpisanie pliku zlecenia: "+ fId.getName()); + } + } catch (ParseException e) { + Log.e(SRV, "Parse", e); + } + }else{ // nowe zlecenie - wywołaj notyfikację. + broadcastNotification(fId.getName()); + } + +// //sprawdzic, czy uploady nowe są z tego zlecenia + File dir = new File(prefs.getString("dir", "")); + File dirUpload = new File(dir + "/upload"); + File dirZlecenie = new File(dirUpload + "/" +id); + if( dirZlecenie.isDirectory()){ + File f[] = dirZlecenie.listFiles(new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.toLowerCase().endsWith(".mod"); + } + }); + if( f.length>0){ + load = false; + Log.d(SRV, "Jest inna modyfikacja w upload"); + } + } + + if( load){ + if( !wczytaneZlecenia.contains(id)){ + //loadToDisk(id); + markOnDisk(id); + + wczytaneZlecenia.add(id); + }else{ + Log.d(SRV, "Zlecenie id: " + id + " juz bylo wczytane"); + } + } + } + } + + + //usun pliki zlecen usunietych + usunPliki(filesToDelete); + + + //rename file + File dListaPrev = new File(prefs.getString("dir", "") + "/baza/lista.profil.work"); + File dListaNew = new File(prefs.getString("dir", "") + "/baza/lista.profil"); + dListaPrev.renameTo(dListaNew); + + + File fconn = new File(prefs.getString("dir", "") + "/dedalsrv.connection"); + if( fconn.exists()){ + fconn.delete(); + } + + } catch (JSONException e) { + // TODO Auto-generated catch block + //e.printStackTrace(); + File fLock = new File(prefs.getString("dir", "") + "/dedalsrv.connection"); + try { + fLock.createNewFile(); + } catch (IOException econ) { + Log.e(SRV, "IO", econ); + } + } + + // wystartuj/obudz serwis + //Context context = getApplicationContext(); + Intent service = new Intent(context, DedalDownloadService.class); + context.startService(service); + + + } + + private void getKp() { + prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); + SharedPreferences.Editor prefsEditor = prefs.edit(); + File KPDirectory = new File(prefs.getString("dir", "") + "/kp_json/"); + if (!KPDirectory.exists()) { + KPDirectory.mkdir(); + } + String KP_filename = KPDirectory.getAbsolutePath() + "/" + "kp.json"; + //String KP_filename_mod = KP_filename.replace(".json", ".mod"); + //DedalHelper.deleteFile(KP_filename_mod); + + prefsEditor.putString("KP_filename", KP_filename); + prefsEditor.commit(); + Log.d("DedalService: KP_filename", KP_filename); + + DedalHttpConnection con = new DedalHttpConnection(getApplicationContext()); + String response_str = con.sendPost("xml/getKPJson.php", null); + Log.d("response_str", response_str); + DedalHelper.putFileContent(KP_filename, response_str); + } + + private void getKpWplaty() { + prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); + SharedPreferences.Editor prefsEditor = prefs.edit(); + File KPDirectory = new File(prefs.getString("dir", "") + "/kp_json/"); + if (!KPDirectory.exists()) { + KPDirectory.mkdir(); + } + String KPWplaty_filename = KPDirectory.getAbsolutePath() + "/" + "kp_wplaty.json"; + //String KP_filename_mod = KP_filename.replace(".json", ".mod"); + //DedalHelper.deleteFile(KP_filename_mod); + + prefsEditor.putString("KPWplaty_filename", KPWplaty_filename); + prefsEditor.commit(); + Log.d("DedalService: KPWplaty_filename", KPWplaty_filename); + + DedalHttpConnection con = new DedalHttpConnection(getApplicationContext()); + String response_str = con.sendPost("xml/getWplatyKpJson.php", null); + Log.d("response_str", response_str); + DedalHelper.putFileContent(KPWplaty_filename, response_str); + } + + private void usunPliki(Vector filesToDelete) { + if(filesToDelete.size()>0 ){ + //files[i].getName() + Log.d(SRV, "jest "+ filesToDelete.size() + " plików do usunięcia:"); + } + + for( int k = 0; k < filesToDelete.size(); k++){ + String name = (String) filesToDelete.elementAt(k); + //filesToDelete + File fToDel = new File(prefs.getString("dir", "") + "/baza/"+name); + fToDel.delete(); + Log.d(SRV, "usunięto plik: "+prefs.getString("dir", "") + "/baza/"+name); + } + } + + private Map wczytajDatyPoprzednichModyfikacji() { + // TODO Auto-generated method stub + Map listaZlecen = new HashMap(); + BufferedReader buf; + try { + String s = DedalHelper.getFileContent(prefs.getString("dir", "") + "/baza/lista.profil"); + if( s!= null && s.length()>0) { + JSONObject jFile = new JSONObject(s); + JSONObject jProfiles = jFile.getJSONObject("profile"); + Iterator pKeys = jProfiles.keys(); + + while (pKeys.hasNext()) { + String idProfilu = (String) pKeys.next(); + JSONObject jProfil = jProfiles.getJSONObject(idProfilu); + if (jProfil.has("zlecenia") && !"[]".equals(jProfil.getString("zlecenia"))) { + JSONObject jZlecenia = new JSONObject(jProfil.getString("zlecenia")); + Iterator keys = jZlecenia.keys(); + while (keys.hasNext()) { + + String id = (String) keys.next(); + JSONObject jZlecenie = jZlecenia.getJSONObject(id); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date dZapis; + try { + dZapis = sdf.parse(jZlecenie.getString("data_zapisu")); + long lastZapis = dZapis.getTime(); + listaZlecen.put(id, lastZapis); + // Log.d(SRV, "Zlecenie ID: "+ id + ", poprzedni czas mod: " + lastZapis); + } catch (ParseException e) { + Log.e(SRV, "", e); + } + } + } + } + } + } catch (JSONException e) { + Log.e(SRV, "", e); + } + return listaZlecen; + } + + + private void uploadKP() { + Log.d("my_debug", "uploadKP"); + File dir = new File(prefs.getString("dir", "")); + File fDstf = new File(dir + "/upload_kp"); + if( !fDstf.isDirectory()){ + fDstf.mkdirs(); + } + File files[] = fDstf.listFiles(); + if( fDstf != null) { + for (int i = 0; i < files.length; i++) { + uploadKPHttp(files[i].getAbsolutePath()); + } + } + } + + private void uploadKPWplaty() { + Log.d("my_debug", "uploadKPWplaty"); + File dir = new File(prefs.getString("dir", "")); + File fDstf = new File(dir + "/upload_kp_wplaty"); + if( !fDstf.isDirectory()){ + fDstf.mkdirs(); + } + File files[] = fDstf.listFiles(); + if( fDstf != null) { + for (int i = 0; i < files.length; i++) { + uploadKPWplatyHttp(files[i].getAbsolutePath()); + } + } + } + + private void uploadWidokProfilModifications() { + Log.d("my_debug", "uploadWidokProfilModifications"); + File dir = new File(prefs.getString("dir", "")); + File fDstf = new File(dir + "/upload_widok_profil_mod"); + if( !fDstf.isDirectory()){ + fDstf.mkdirs(); + } + File files[] = fDstf.listFiles(); + if( fDstf != null) + for (int i=0; i params_post = new HashMap(); + params_post.put("kp_json", DedalHelper.getFileContent(namePath)); + String response = con.sendPost("xml/setKPJson.php", params_post); + + if( "true".equals(response) ) { + //delete mod + String KP_filename = prefs.getString("KP_filename", ""); + String KP_filename_mod = KP_filename.replace(".json", ".mod"); + DedalHelper.deleteFile(KP_filename_mod); + DedalHelper.deleteFile(namePath); + } + else { + Log.d("SVC", "problem with upload kp, response: " + response); + } + } + + private void uploadKPWplatyHttp(String namePath) { + DedalHttpConnection con = new DedalHttpConnection(getApplicationContext()); + Map params_post = new HashMap(); + params_post.put("ids_wplat", DedalHelper.getFileContent(namePath)); + String response = con.sendPost("xml/updateWplatyKpJson.php", params_post); + + if( "true".equals(response) ) { + //delete mod + DedalHelper.deleteFile(namePath); + } + else { + Log.d("SVC", "problem with upload kp wplaty, response: " + response); + } + } + + private void uploadWidokProfilHttp(String namePath) { + ServerCommunication(); + //Log.d("my_debug", "upload zlecenie"); + try { + //Log.d(SRV, "uploading HTML urlencoded file... :" + namePath); + String sJson = DedalHelper.getFileContent(namePath); + Log.d(SRV, "JSON: " + sJson); + Log.d("my_debug", "namePath: "+namePath+", JSON: " + sJson); + JSONObject js = new JSONObject(sJson); + + String login = prefs.getString("user", ""); + String pass = DedalHelper.decodeB64(prefs.getString("password", "")); + HttpPost httppost = new HttpPost( hostPath + "/public/change_widok_profil_user.php"); +// + httppost.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded")); + httppost.setHeader(new BasicHeader("charset", "UTF-8")); +// +// + List parameters = new ArrayList(); + parameters.add(new BasicNameValuePair( "login", login )); + parameters.add(new BasicNameValuePair( "pass", pass )); + + int nr = 1; + if( js.has("profil_kolumny") && js.has("id_profilu") ) { + JSONArray jKolumny = js.getJSONArray("profil_kolumny"); + String id_profilu = js.getString("id_profilu"); + for( int k=0; k< jKolumny.length(); k++) + { + String kod = jKolumny.getJSONObject(k).getString("kod"); + String nazwa = jKolumny.getJSONObject(k).getString("nazwa"); + + //parameters.add(new BasicNameValuePair("nr", Integer.toString(k))); + nr = k + 1; + parameters.add(new BasicNameValuePair("kod-"+nr, kod)); + //parameters.add(new BasicNameValuePair("nazwa", nazwa)); + } + parameters.add(new BasicNameValuePair("id_profilu", id_profilu)); + } + if( js.has("id_profilu") && js.has("reset") && "true".equals(js.getString("reset")) ) { + parameters.add(new BasicNameValuePair("id_profilu", js.getString("id_profilu"))); + parameters.add(new BasicNameValuePair("reset", "true")); + } + //parameters.add(new BasicNameValuePair("sub", "Zapisz zmiany")); + + httppost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8")); + + + Log.d(SRV, "Entity BasicNameValuePair zaladowane"); + + HttpResponse response = mHttpClient.execute(httppost); + if( response != null){ //todo sprawdzic, czy udalo się usunąć + HttpEntity r_entity = response.getEntity(); + String responseString = EntityUtils.toString(r_entity); + Log.d("my_debug", "response from change_widok_profile: "+responseString); + File fToDel = new File( namePath); + if( fToDel.exists()){ + fToDel.delete(); + } + } + + } catch (Exception e) { + Log.e(SRV, "", e); + } + + } + + private void uploadFolderOrderHttp(String namePath) { + ServerCommunication(); + //Log.d("my_debug", "upload zlecenie"); + try { + //Log.d(SRV, "uploading HTML urlencoded file... :" + namePath); + String sJson = DedalHelper.getFileContent(namePath); + Log.d(SRV, "JSON: " + sJson); + Log.d("my_debug", "namePath: "+namePath+", JSON: " + sJson); + JSONObject js = new JSONObject(sJson); + +// File fToDel = new File( namePath); +// if( fToDel.exists()){ +// fToDel.delete(); +// } + +// String id_zlecenia = js.getString("id_zlecenia"); +// + String login = prefs.getString("user", ""); + String pass = DedalHelper.decodeB64(prefs.getString("password", "")); + HttpPost httppost = new HttpPost( hostPath + "/public/change_folder_order.php"); +// + httppost.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded")); + httppost.setHeader(new BasicHeader("charset", "UTF-8")); +// +// + List parameters = new ArrayList(); + + parameters.add(new BasicNameValuePair( "login", login )); + parameters.add(new BasicNameValuePair( "pass", pass )); + + parameters.add(new BasicNameValuePair("id_folder", js.getString("id_folder"))); + if(js.has("kolejnosc")) { + JSONArray ja = js.getJSONArray("kolejnosc"); + for( int i = 0 ; i parameters = new ArrayList(); + parameters.add(new BasicNameValuePair( "login", login )); + parameters.add(new BasicNameValuePair( "pass", pass )); + + if( js.has("zlecenie") ) { + JSONObject jZl = js.getJSONObject("zlecenie"); + + parameters.add(new BasicNameValuePair("id_zlecenia", jZl.getString("id_zlecenia"))); + parameters.add(new BasicNameValuePair("id_folder", jZl.getString("id_folder"))); + } + else if( js.has("new_folder") ) { + JSONObject jZl = js.getJSONObject("new_folder"); + parameters.add(new BasicNameValuePair("nazwa", jZl.getString("nazwa"))); + parameters.add(new BasicNameValuePair("operation", "new_folder")); + } + else if( js.has("delete_folder") ) { + JSONObject jZl = js.getJSONObject("delete_folder"); + parameters.add(new BasicNameValuePair("id_folder", jZl.getString("id_folder"))); + parameters.add(new BasicNameValuePair("operation", "delete_folder")); + } + else if( js.has("edit_folder") ) { + JSONObject jZl = js.getJSONObject("edit_folder"); + parameters.add(new BasicNameValuePair("id_folder", jZl.getString("id_folder"))); + parameters.add(new BasicNameValuePair("nazwa", jZl.getString("nazwa"))); + parameters.add(new BasicNameValuePair("operation", "edit_folder")); + } + //parameters.add(new BasicNameValuePair("sub", "Zapisz zmiany")); + + httppost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8")); + + + Log.d(SRV, "Entity BasicNameValuePair za�adowane"); + + HttpResponse response = mHttpClient.execute(httppost); + if( response != null){ //todo sprawdzic, czy udalo si� usun�� + HttpEntity r_entity = response.getEntity(); + String responseString = EntityUtils.toString(r_entity); + Log.d("my_debug", responseString); + File fToDel = new File( namePath); + if( fToDel.exists()){ + fToDel.delete(); + } + } + + } catch (Exception e) { + Log.e(SRV, "", e); + } + + } + + private void uploadZlecenieHttp(String namePath) { + ServerCommunication(); + //Log.d("my_debug", "upload zlecenie"); + try { + Log.d(SRV, "uploading HTML urlencoded file... :" + namePath); + String sJson = DedalHelper.getFileContent(namePath); + Log.d(SRV, "JSON: " + sJson); + JSONObject js = new JSONObject(sJson); + String id_zlecenia = js.getString("id_zlecenia"); + //id_zlecenia, folder + String login = prefs.getString("user", ""); + String pass = DedalHelper.decodeB64(prefs.getString("password", "")); + HttpPost httppost = new HttpPost( hostPath + "/public/mobi.php?id_zlecenia="+id_zlecenia); +// + httppost.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded")); + httppost.setHeader(new BasicHeader("charset", "UTF-8")); + + + List parameters = new ArrayList(); + parameters.add(new BasicNameValuePair( "login", login )); + parameters.add(new BasicNameValuePair( "pass", pass )); + //petla.. + + JSONObject pola = js.getJSONObject("pola"); + + try { + Iterator k = pola.keys(); + while (k.hasNext()) { + String key = (String) k.next(); + + JSONObject jo = pola.getJSONObject(key); + dodajParams( jo, parameters); + } + + } catch (JSONException e) { + Log.e(SRV, "", e); + } + + + /// GPS /// + if( js.has("gps") ) { + Log.d("my_debug", "zlecenie gps"); + JSONObject gps = js.getJSONObject("gps"); + //Log.d("my_debug", "nana"); + try { + Iterator k = gps.keys(); + while (k.hasNext()) { + String key = (String) k.next(); + parameters.add(new BasicNameValuePair( key, gps.getString(key))); +// JSONObject jo = gps.getJSONObject(key); +// dodajParams(jo, parameters); + } + //Log.d("my_debug", "3upload: "+namePath); + + } catch (JSONException e) { + Log.e(SRV, "JSON", e); + } + } + /// GPS /// + + if( js.has("sub_stat_acc") ) { + parameters.add(new BasicNameValuePair("sub_stat_acc", js.getString("sub_stat_acc"))); + //Log.d("my_debug", "sub: "+js.getString("sub")); + } + + if( js.has("sub") ) { + parameters.add(new BasicNameValuePair("sub", js.getString("sub"))); + //Log.d("my_debug", "sub: "+js.getString("sub")); + } + else { + parameters.add(new BasicNameValuePair("sub", "Zapisz zmiany")); + //Log.d("my_debug", "sub - def: Zapisz zmiany"); + } + + parameters.add(new BasicNameValuePair("page", "wynik")); + //parameters.add(new BasicNameValuePair("sub", "Zapisz zmiany")); + + httppost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8")); + + + Log.d(SRV, "Entity BasicNameValuePair załadowane"); + Log.d(SRV, "host: "+hostPath + "/public/mobi.php?id_zlecenia="+id_zlecenia+"&login="+login+"&pass="+pass); + + HttpResponse response = mHttpClient.execute(httppost); + if( response != null){ //todo sprawdzic, czy udalo się, usun + + int respCode = response.getStatusLine().getStatusCode(); + //String h = response.getHeaders(); + + HttpEntity r_entity = response.getEntity(); + + String responseString = EntityUtils.toString(r_entity); + Log.d(SRV, "aktualizacja zlecenia HTTP code:" + respCode + " - response: "+responseString); + /// response log +//"Formularz zapisano" + //todo: wielojęzyczność - specjalny kod w HTML dodać. + if( !responseString.contains("Formularz zapisano")){ //responseString.contains("login_change")){ + Log.e(SRV, "login_change: Nie udalo sie wyslac zlecenia: "+ namePath); + File fLockCon = new File(prefs.getString("dir", "") + "/dedalsrv.connection_password"); + try { + fLockCon.createNewFile(); + } catch (IOException econ) { + Log.e(SRV, "", econ); + } + + + }else{ + File fToDel = new File( namePath); + if( fToDel.exists()){ + fToDel.delete(); + } + File fLockCon = new File(prefs.getString("dir", "") + "/dedalsrv.connection_password"); + if( fLockCon.exists()){ + fLockCon.delete(); + } + } + + }else{ + Log.e(SRV, "Nie udalo sie wyslac zlecenia: "+ namePath); + } + + } catch (Exception e) { + //e.printStackTrace(); + Log.e(SRV, "", e); + } + } + private void dodajParams(JSONObject jo, List parameters) { + // + //parameters.add(new BasicNameValuePair("zlecenie", xml)); + //JSONArray k = js; + try { + + if( !jo.has("no-sent") ) { + String name = null; + if( jo.has("id-orig")) { + name = "val_"+jo.getString("id-orig")+"-new[]"; + //parameters.add(new BasicNameValuePair( "val_"+jo.getString("id")+"-usun", jo.getString("wartosc")) ); + parameters.add(new BasicNameValuePair( "pow_"+jo.getString("id-orig")+"-tablet[]", jo.getString("id")) ); + } + + if (!jo.has("id-orig") && jo.has("id")) { + name = "val_"+jo.getString("id"); + } + + if(jo.has("usun") && jo.getString("usun").equals("true") ) { + if( !jo.has("id-orig") ) { + name = "val_"+jo.getString("id")+"-usun"; + } + else { + parameters.add(new BasicNameValuePair( "usun-id_tablet[]", jo.getString("id")) ); + } + } + if (name != null && !"foto".equals(jo.getString("typ_danych")) && jo.has("wartosc") ) { + String wartosc = jo.getString("wartosc"); + if( !"h".equals(wartosc)) { + parameters.add(new BasicNameValuePair(name, wartosc)); + } + } + + // ID DŁUŻNIKA W POLACH ACCEPT + if( jo.has("klient") && "accept".equals(jo.getString("klient")) && jo.has("id_dluznika")) { + Log.d("DedalService", "id_dluznika od wyslania: "+jo.getString("id_dluznika")); + parameters.add(new BasicNameValuePair( "val_dluznik_"+jo.getString("id"), jo.getString("id_dluznika")) ); + } + } + + JSONArray ja = jo.getJSONArray("childs"); + if( ja!= null && ja.length()>0){ + for ( int i=0; i parameters = new ArrayList(); + HttpPost httppost; +// httppost = new HttpPost( hostPath + "/public/zalaczniki_foto_add.php" ); + httppost = new HttpPost( hostPath + "/public/zalaczniki_add.php" ); + if( !folder.equals("foto_typ") ) { + parameters.add(new BasicNameValuePair( "folder", folder )); + } + parameters.add(new BasicNameValuePair( "login", login )); + parameters.add(new BasicNameValuePair( "pass", pass )); + parameters.add(new BasicNameValuePair( "usun", fToDel )); + parameters.add(new BasicNameValuePair( "id_zlecenia", id_zlecenia )); + httppost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8")); + + HttpResponse response = mHttpClient.execute(httppost); + if( response != null){ //todo sprawdzic, czy udalo si� usun�� + HttpEntity r_entity = response.getEntity(); + String responseString = EntityUtils.toString(r_entity); + Log.d(SRV, responseString); + image.delete(); + } + + } catch (Exception e) { + //e.printStackTrace(); + Log.e(SRV, "", e); + } + } + + private void uploadUserPhoto(File image, String id_zlecenia, String folder) { + ServerCommunication(); + try { + if( folder.equals("foto_typ") ) { + Log.d(SRV, "Uploading file... :" + image.getAbsolutePath()); + Log.d("my_debug", "Uploading file... :" + image.getAbsolutePath()); + Log.d("my_debug", "zdjecie foto_typ"); + HttpPost httppost = new HttpPost( hostPath + "/public/zalaczniki_foto_add.php?id_zlecenia="+id_zlecenia); + + //FileBody fileBody = new FileBody(image); + //ByteArrayBody(byte[] data, ContentType contentType, String filename) + byte[] imageBytes = DedalHelper.getFileContent(image.getAbsolutePath()).getBytes(); + byte[] bytes = DedalHelper.decodeFile(imageBytes); + ByteArrayBody byteBody = new ByteArrayBody(bytes, image.getName()); + MultipartEntityBuilder builder = MultipartEntityBuilder.create() + .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) + .addTextBody("login", login ) + .addTextBody("pass", pass ) + .addPart("dodaj", byteBody); + HttpEntity multiPartEntity = builder.build(); + httppost.setEntity(multiPartEntity); + + HttpResponse response = mHttpClient.execute(httppost); + //Log.d("my_debug", "response po zdjeciu: "+response); + if( response != null){ + HttpEntity r_entity = response.getEntity(); + String responseString = EntityUtils.toString(r_entity); + Log.d(SRV, responseString); + image.delete(); + } + } + else { + if ( image.exists() ) { + Log.d(SRV, "Uploading file... :" + image.getAbsolutePath()); + HttpPost httppost = new HttpPost(hostPath + "/public/zalaczniki_add.php?folder=" + folder + "&id_zlecenia=" + id_zlecenia); + + MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); + entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); + entityBuilder.addTextBody("login", login ) + .addTextBody("pass", pass ); + + //FileBody fileBody = new FileBody(image); + if ("log_file".equals(id_zlecenia)) { + if( image.lastModified() + 1000*3600*24*3 < System.currentTimeMillis() ){ + //ignore too old: + Log.e("LOG_TOO_OLD", "za stary log, ignorowanie:" + image.getName()); + if( image.lastModified() + 1000*3600*24*14 < System.currentTimeMillis() ){ + //usuń starsze niż 14 dni. + Log.e("LOG_TOO_OLD", "za stary log, USUWANIE:" + image.getName()); + image.delete(); + } + return; + } + if( image.length() > 10000000){ + Log.e("LOG_TOO_BIG", "za duzy log, ignorowanie: " + image.getName()); + //image.delete(); + return; + } + entityBuilder.addPart("log_file", new FileBody(image)); + } else { + //entityBuilder.addBinaryBody("dodaj", image); + byte[] imageBytes = DedalHelper.getCryptFileBytes(image.getAbsolutePath()); + ByteArrayBody byteBody = new ByteArrayBody(imageBytes, image.getName()); + entityBuilder.addPart("dodaj", byteBody); + } + HttpEntity entity = entityBuilder.build(); + httppost.setEntity(entity); + + HttpResponse response = mHttpClient.execute(httppost); + //Log.d("my_debug", "response po zdjeciu: "+response); + if (response != null) { + HttpEntity r_entity = response.getEntity(); + String responseString = EntityUtils.toString(r_entity); + Log.d(SRV, "responseString: " + responseString); + if ("log_file".equals(id_zlecenia)) { + if (responseString != null) { + String trimResponseString = responseString.trim(); + if ( trimResponseString.indexOf("true") >= 0 ) { + image.delete(); + } + } + } else { + image.delete(); + } + } + } + else { + Log.d(SRV, "file to uplaod doesn't exists: "+image.getAbsolutePath()); + } + } + + + } catch (Exception e) { + //e.printStackTrace(); + Log.e(SRV, "", e); + //e.printStackTrace(); + // Log.e(ServerCommunication.class.getName(), e.getLocalizedMessage(), e); + } + } + + + public void ServerCommunication() { + mHttpClient = DedalService.getNewHttpClient(); + } + + void markOnDisk(String m_id) { + File myDir = new File(prefs.getString("dir", "") + "/queue"); + if( !myDir.isDirectory()){ + myDir.mkdirs(); + } + File d_queue_prio = new File(prefs.getString("dir", "") + "/queue_prio"); + if( !d_queue_prio.isDirectory()){ + d_queue_prio.mkdirs(); + } + + File myFile = new File(prefs.getString("dir", "") + "/queue/"+m_id); + FileOutputStream fos; + try { + fos = new FileOutputStream(myFile); + fos.write("".getBytes()); + fos.flush(); + fos.close(); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + public DedalService() { + } + + @Override + public IBinder onBind(Intent intent) { + // TODO: Return the communication channel to the service. + throw new UnsupportedOperationException("Not yet implemented"); + } + + + Notification.Builder nB; + public static final int NOTIFICATION_ID=1; + /* (non-Javadoc) + * @see android.app.Service#onCreate() + */ + @Override + public void onCreate() { + // TODO Auto-generated method stub + super.onCreate(); + + Log.d(SRV, "Service DedalService created."); + nB = new Notification.Builder(this); + //nB.setAutoCancel(true) + nB.setTicker("Przyszło nowe zlecenie"); + nB.setSmallIcon(R.drawable.ic_launcher); + //icon? + + } + + private void broadcastNotification(String name){ + Intent startIntent = new Intent( this, MainActivity.class); + File f = new File(prefs.getString("dir", "") + "/baza/" + name); + Uri u = Uri.fromFile(f); + startIntent.setData(u); + //startActivity(intent); + + PendingIntent launchIntent = PendingIntent.getActivity(this, 0, startIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); + + nB.setContentIntent(launchIntent); + Date d = new Date(); + //nB.setWhen(d.getTime ()); + nB.setWhen(System.currentTimeMillis()); + nB.setContentTitle("zlecenie nr: " + name); + nB.setContentText("priorytet 1 "); + + NotificationManager nM = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); + // Android 13+ requires POST_NOTIFICATIONS runtime permission + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { + Log.d(SRV, "Notification not sent: missing POST_NOTIFICATIONS permission."); + return; + } + } + // nM.notify(NOTIFICATION_ID, nB.getNotification()); + nM.notify(NOTIFICATION_ID, nB.build()); + Log.d(SRV, "Nofification sent."); + + } + + /* (non-Javadoc) + * @see android.app.Service#onDestroy() + */ + @Override + public void onDestroy() { + // TODO Auto-generated method stub + if( thread != null) + { + isStopped = true; + thread.interrupt(); + } + try { + thread.join(); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + //e.printStackTrace(); + Log.e(SRV, "", e); + } + super.onDestroy(); + } + + /* (non-Javadoc) + * @see android.app.Service#onLowMemory() + */ + @Override + public void onLowMemory() { + // TODO Auto-generated method stub + super.onLowMemory(); + } + + GPSTracker gps; + /* (non-Javadoc) + * @see android.app.Service#onStartCommand(android.content.Intent, int, int) + */ + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + // TODO Auto-generated method stub + Log.d(SRV, "Service onStartCommand called."); + Log.d(SRV, "Intent: " + intent + ", flags: " + flags + ", startId: " + startId); + + + gps = new GPSTracker(this); +// gps = ListActivity.gps; + gps.getLocation(); + + // broadcastNotification("973009595.json"); + Context context = getApplicationContext(); + prefs = PreferenceManager.getDefaultSharedPreferences(context); + Log.setFileName(prefs.getString("dir", "")); + Log.setEH(); + + if( thread == null){ + + // temporary HTTPS!!! EOS pre-produkcja + + // utworzyć strukturę katalogów + File d = new File(prefs.getString("dir", "") + "/baza"); + d.mkdirs(); + d = new File(prefs.getString("dir", "") + "/upload"); + d.mkdirs(); + d = new File(prefs.getString("dir", "") + "/mDedal"); + d.mkdirs(); + d = new File(prefs.getString("dir", "") + "/mDedalCam"); + d.mkdirs(); + + File myDir = new File(prefs.getString("dir", "") + "/queue"); + if( !myDir.isDirectory()){ + myDir.mkdirs(); + } + File d_queue_prio = new File(prefs.getString("dir", "") + "/queue_prio"); + if( !d_queue_prio.isDirectory()){ + d_queue_prio.mkdirs(); + } + + + + startThread(); + }else{ +// Context context = getApplicationContext(); +// prefs = PreferenceManager.getDefaultSharedPreferences(context); + File fNext = new File(prefs.getString("dir", "") + "/dedalsrv.continue"); + try { + fNext.createNewFile(); + } catch (IOException e) { + //e.printStackTrace(); + Log.e(SRV, "", e); + } + if( thread.isAlive()){ + thread.interrupt(); + }else{ + Log.d(SRV, "Watek serwisu byl zatrzymany. Restart watku"); + startThread(); + } + } + + return super.onStartCommand(intent, flags, startId); + } + + Thread thread = null; + private void startThread(){ + Log.d(SRV, "Start watku Serwisu."); + thread = new Thread(new WorkingThread()); + thread.start(); + + } + private HttpClient mHttpClient; + + String readFile(InputStream in) throws IOException { + StringBuffer sb = new StringBuffer(); + byte buffer[] = new byte[10000]; + int s = 0; + while ((s = in.read(buffer)) > 0) { + String st =new String(buffer, 0, s); + //Log.d(SRV, "i=" + s +", data:" + st); + sb.append(st); + } + return sb.toString(); + } +} diff --git a/app/src/main/java/com/likesoft/mdedal/DokumentyKollektoActivity.java b/app/src/main/java/com/likesoft/mdedal/DokumentyKollektoActivity.java new file mode 100644 index 0000000..755be1c --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/DokumentyKollektoActivity.java @@ -0,0 +1,655 @@ +package com.likesoft.mdedal; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Iterator; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import android.app.Activity; +import android.app.ActivityManager; +import android.app.ActivityManager.RunningServiceInfo; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Color; +import android.net.Uri; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.HorizontalScrollView; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TableLayout; +import android.widget.TableRow; +import android.widget.TextView; + +public class DokumentyKollektoActivity extends Activity { + + LinearLayout lMain; + String id_zlecenia; + JSONArray dkJson; + SharedPreferences prefs; + boolean refreshingLista = true; + + private final class rowOpenFileListener implements OnClickListener { + File file; + public rowOpenFileListener (File file) { + this.file = file; + } + + @Override + public void onClick(View v) { + try { + openFile(getApplicationContext(), file); + } catch (IOException e) { + Log.e("DEDAL", "IO", e); + } + } + } + + private final class rowDownloadFileListener implements OnClickListener { + String fileName; + public rowDownloadFileListener (String fileName) { + this.fileName = fileName; + } + + @Override + public void onClick(View v) { + // obłsuga pliku do komunikacji z serwerem + //String commPath = prefs.getString("dir", "") + "/pliki_kollekto/communication.json"; + //File myFile = new File(commPath); + + Long time = (System.currentTimeMillis()); + String ts = Long.toString(time); + String commPath = prefs.getString("dir", "") + "/pliki_kollekto/comm_"+ts+".json"; + //File myFile = new File(commPath); + + String commJsString = readFile(commPath); + JSONObject commJs = null; + if( "".equals(commJsString) ) { + commJs = new JSONObject(); + } + else { + try { + commJs = new JSONObject(commJsString); + } catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + } + } + + try { + JSONObject zlecJs; + if( commJs.has(id_zlecenia) ) { + zlecJs = commJs.getJSONObject(id_zlecenia); + } + else { + zlecJs = new JSONObject(); + } + zlecJs.put(fileName, "get"); + commJs.put(id_zlecenia, zlecJs); + } catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + } + + writeFile(commPath, commJs.toString()); + + + // obsługa pliku zawierającym statusy + String statPath = prefs.getString("dir", "") + "/pliki_kollekto/statuses.json"; + File myFile = new File(statPath); + String statJsString = readFile(statPath); + JSONObject statJs = null; + if( "".equals(statJsString) ) { + statJs = new JSONObject(); + } + else { + try { + statJs = new JSONObject(statJsString); + } catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + } + } + + //zlecJs = new JSONObject(); + try { + JSONObject zlecJs; + if( statJs.has(id_zlecenia) ) { + zlecJs = statJs.getJSONObject(id_zlecenia); + } + else { + zlecJs = new JSONObject(); + } + zlecJs.put(fileName, "Żądanie pobrania"); + statJs.put(id_zlecenia, zlecJs); + } catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + } + + writeFile(statPath, statJs.toString()); + + //wystartuj/obudz servis + startDokumentyKollektoService(); + + DokumentyKollektoActivity.this.recreate(); + } + } + + private final class btnDeleteFileListener implements OnClickListener { + String fileName; + public btnDeleteFileListener (String fileName) { + this.fileName = fileName; + } + + @Override + public void onClick(View v) { + try { + File myFile = new File(prefs.getString("dir", "") + "/pliki_kollekto/"+id_zlecenia+"/"+fileName); + if( myFile.exists() ) { + myFile.delete(); + } + + //String commPath = prefs.getString("dir", "") + "/pliki_kollekto/communication.json"; + Long time = (System.currentTimeMillis()); + String ts = Long.toString(time); + String commPath = prefs.getString("dir", "") + "/pliki_kollekto/comm_"+ts+".json"; + + //String commJsString = readFile(commPath); + + JSONObject commJs = new JSONObject(); + JSONObject zlJs; + if( commJs.has(id_zlecenia) ) { + zlJs = commJs.getJSONObject(id_zlecenia); + } + else { + zlJs = new JSONObject(); + } + //JSONObject zlJs = commJs.getJSONObject(id_zlecenia); + //if( zlJs.has(fileName) ) { + zlJs.put(fileName, "delete"); + commJs.put(id_zlecenia, zlJs); + + writeFile(commPath, commJs.toString()); + + // obsługa pliku zawierającym statusy + String statPath = prefs.getString("dir", "") + "/pliki_kollekto/statuses.json"; + String statJsString = readFile(statPath); + JSONObject statJs = null; + //if( "".equals(statJsString) ) { + statJs = new JSONObject(statJsString); + //zlJs = statJs.getJSONObject(id_zlecenia); + if( statJs.has(id_zlecenia) ) { + zlJs = statJs.getJSONObject(id_zlecenia); + } + else { + zlJs = new JSONObject(); + } + zlJs.put(fileName, "Do pobrania"); + statJs.put(id_zlecenia, zlJs); + writeFile(statPath, statJs.toString()); + //} + + //wystartuj/obudz servis + startDokumentyKollektoService(); + + DokumentyKollektoActivity.this.recreate(); + + //} + + } catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + } + } + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + Context context = getApplicationContext(); + prefs = PreferenceManager.getDefaultSharedPreferences(context); + Log.setFileName(prefs.getString("dir", "")); + Log.setEH(); + + refreshingLista = true; + upServiceIfNeeded(); + + HorizontalScrollView lMainScroll = new HorizontalScrollView(this); + lMain = new LinearLayout(this); + lMain.setOrientation(LinearLayout.VERTICAL); + + ScrollView vertScroll = new ScrollView(this); + lMainScroll.addView(vertScroll); + + vertScroll.addView(lMain); + + Bundle extras = getIntent().getExtras(); + if (extras != null) { + id_zlecenia = extras.getString("id_zlecenia"); + try { + dkJson = new JSONArray(extras.getString("dkJson")); + } catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + } + Log.d("my_debug", "dokumentyKollektoActivity, id_zlecenia: "+id_zlecenia+", dkJson: "+dkJson.toString()); + } + + //TextView tv = new TextView(this); + //tv.setText("Dostępne dokumenty"); + //lMain.addView(tv); + + + wyswietlListe(); + + + setContentView(lMainScroll); + + this.setTitle("Dokumenty Kollekto, id_zlecenia: "+id_zlecenia); + + // wtatek który sprawdza czy zmienil sie plik: statuses.json. Jesli tak to odswiez liste. + Thread t =new Thread(new Runnable() { + + @Override + public void run() { + // TODO Auto-generated method stub + Long lastMod = null; + Long lastStatMod = null; + while( true ){ + if( !refreshingLista ) { + break; + } + try { + + File dLista = new File(prefs.getString("dir", "") + "/pliki_kollekto/statuses.json"); + if( dLista.isFile()){ + lastMod = dLista.lastModified(); + if (lastStatMod == null) { lastStatMod = lastMod; continue; } + //Log.d("my_debug", lastStatMod+ " | " +lastMod); + if ( !lastStatMod.equals(lastMod) ) { + lastStatMod = lastMod; + Log.d("my_debug", "DokumentyKollektoActivity: odswieżam liste"); + //DokumentyKollektoActivity.this.recreate(); + //DokumentyKollektoActivity.this.reload(); + lMain.post(new Runnable() { + + @Override + public void run() { + wyswietlListe(); + } + }); + + + } + } + Thread.sleep(1000); + } catch (InterruptedException e) { + break; + } + } + } + }); + t.start(); + } + + private void wyswietlListe(){ + + lMain.removeAllViews(); + + + + int colNum = 5; + TableLayout tl = new TableLayout(DokumentyKollektoActivity.this); + lMain.addView(tl); + tl.setPadding(0, 15, 0, 0); + TableRow rowHeader = new TableRow(DokumentyKollektoActivity.this); + tl.addView(rowHeader); + rowHeader.setBackgroundColor(Color.parseColor("#FFA500")); + TextView[] tvHeaders = new TextView[colNum]; + for(int i = 0; i < colNum; i++) { + tvHeaders[i] = new TextView(DokumentyKollektoActivity.this); + rowHeader.addView(tvHeaders[i]); + tvHeaders[i].setPadding(5, 3, 5, 2); + tvHeaders[i].setTextSize(25); + //tvHeaders[i].setBackgroundColor(Color.parseColor("#FFA500")); + } + tvHeaders[0].setText("Nazwa pliku"); + tvHeaders[1].setText("Typ"); + tvHeaders[2].setText("Opis"); + tvHeaders[3].setText("Rozmiar"); + tvHeaders[4].setText("Status"); + + String statPath = prefs.getString("dir", "") + "/pliki_kollekto/statuses.json"; + //File statFile = new File(statPath); + String statJsString = readFile(statPath); + JSONObject statJs = null; + JSONObject zlecStatJs = null; + try { + if( !"".equals(statJsString) ) { + statJs = new JSONObject(statJsString); + if( statJs.has(id_zlecenia) ) { + zlecStatJs = statJs.getJSONObject(id_zlecenia); + } + } + } catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + } + + JSONObject oneDokJson; + try { + // lista plików + for( int i=0 ; i < dkJson.length() ; i++) { + boolean pobrany = false; + boolean btnUsunBool = false; + oneDokJson = dkJson.getJSONObject(i); + TableRow rowDok = new TableRow(DokumentyKollektoActivity.this); + tl.addView(rowDok); + TextView[] tvDok = new TextView[colNum]; + for(int j = 0; j < colNum; j++) { + tvDok[j] = new TextView(DokumentyKollektoActivity.this); + tvDok[j].setPadding(5, 3, 5, 2); + tvDok[j].setTextSize(25); + rowDok.addView(tvDok[j]); + } + String fileName = oneDokJson.getString("nazwa_pliku"); + tvDok[0].setText(fileName); + tvDok[1].setText(oneDokJson.getString("typ")); + tvDok[2].setText(oneDokJson.getString("opis")); + tvDok[3].setText(oneDokJson.getString("rozmiar")); + String status = ""; + + // czytam status z pliku statuses.json + if( zlecStatJs != null && zlecStatJs.has(fileName) ) { + status = zlecStatJs.getString(fileName); + if("Pobrany".equals(status)) { + pobrany = true; + btnUsunBool = true; + } + if("Żądanie pobrania".equals(status)) { + btnUsunBool = true; + } + + } + // czytam status ze json'a w zleceniu + else { +// if( "null".equals(oneDokJson.getString("data_pobrania")) ) { +// status = "Do pobrania"; +// } +// else { +// btnUsunBool = true; +// pobrany = true; +// } + + if( oneDokJson.has("status") ) { + status = oneDokJson.getString("status"); + } + else { + if( "null".equals(oneDokJson.getString("data_pobrania")) ) { + status = "Do pobrania"; + } + else { + btnUsunBool = true; + pobrany = true; + } + } + + if ( !"Do pobrania".equals(status) ) { + btnUsunBool = true; + } + if ( "Pobrany".equals(status) ) { + pobrany = true; + } + + } + + if( "Do pobrania".equals(status) ) { + rowDok.setOnClickListener(new rowDownloadFileListener(fileName)); + rowDok.setBackgroundColor(Color.YELLOW); + } + + if( pobrany ) { + String path = prefs.getString("dir", "") + "/pliki_kollekto/"+id_zlecenia; + File myFile = new File(path+"/"+fileName); + if( myFile.exists()) { + status = "Pobrany, zobacz"; + rowDok.setOnClickListener(new rowOpenFileListener(myFile)); + + rowDok.setBackgroundColor(Color.GREEN); + } + else { + status = "Błąd - pobrany, jednak nie ma go na tablecie"; + } + } + tvDok[4].setText(status); + + if( btnUsunBool ) { + Button btnUsun = new Button(getApplicationContext()); + btnUsun.setText("Usuń"); + btnUsun.setOnClickListener(new btnDeleteFileListener(fileName)); + rowDok.addView(btnUsun); + } + + + + } + + //Log.d("my_debug", "Dokumenty kollekto, zlecStatJs: " + statJs.toString()); + if( statJs != null && statJs.has("limit") && "true".equals( statJs.getString("limit") ) ) { + Log.d("my_debug", "Dokumenty Kollekto: osiognieto limit"); + TextView warningTv = new TextView(DokumentyKollektoActivity.this); + warningTv.setText("Osiągnięto limit ilości dokumentów. Usuń niepotrzebne dokumenty aby pobrać nowe."); + lMain.addView(warningTv); + } + } catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + } + + + + + + } + + private boolean upServiceIfNeeded() { + // TODO Auto-generated method stub + boolean ret = false; + Log.d("my_debug", "upServiceIfNeeded, DokumentyKollektoService.stopService: "+ DokumentyKollektoService.stopService); + if ( DokumentyKollektoService.stopService ) { + try { + +// String commPath = prefs.getString("dir", "") + "/pliki_kollekto/communication.json"; +// String commJsString = readFile(commPath); +// Log.d("my_debug", "commfile: "+commJsString); +// if ( "".equals(commJsString) || commJsString == null ) { +// return ret; +// } + + File dir = new File(prefs.getString("dir", "")); + File fDstf = new File(dir + "/pliki_kollekto"); + if( !fDstf.isDirectory()){ + fDstf.mkdirs(); + } + File files[] = fDstf.listFiles(); + String commJsString = ""; + boolean keepService = false; + if( fDstf != null) { + for (int i=0; i serviceClass) { + ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); + for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { + if (serviceClass.getName().equals(service.service.getClassName())) { + return true; + } + } + return false; + } + + private void startDokumentyKollektoService() { + // wystartuj/obudz serwis + Log.d("my_debug", "startDokumentyKollektoService, DokumentyKollektoService.stopService: "+ DokumentyKollektoService.stopService); + if ( DokumentyKollektoService.stopService ) { + Context context = getApplicationContext(); + Intent service = new Intent(context, DokumentyKollektoService.class); + context.startService(service); + } + } + + @Override + protected void onDestroy() { + // TODO Auto-generated method stub + refreshingLista = false; + //DokumentyKollektoService.stopService = true; + super.onDestroy(); + + //onDestroyD(this); + } +} diff --git a/app/src/main/java/com/likesoft/mdedal/DokumentyKollektoService.java b/app/src/main/java/com/likesoft/mdedal/DokumentyKollektoService.java new file mode 100644 index 0000000..89bf832 --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/DokumentyKollektoService.java @@ -0,0 +1,266 @@ +package com.likesoft.mdedal; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.json.JSONException; +import org.json.JSONObject; + +import android.app.Service; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.IBinder; +import android.preference.PreferenceManager; + +public class DokumentyKollektoService extends Service { + + public static boolean stopService = true; + SharedPreferences prefs; + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); + stopService = false; + // TODO Auto-generated method stub + Thread t = new Thread(new Runnable() { + @Override + public void run() { + //tutaj będzie akcja + + while ( true ) { + if( stopService ) { + break; + } + + try { + Log.d("my_debug", "DokumentyKollektoService"); + + File dir = new File(prefs.getString("dir", "")); + File fDstf = new File(dir + "/pliki_kollekto"); + if( !fDstf.isDirectory()){ + fDstf.mkdirs(); + } + File files[] = fDstf.listFiles(); + String commJsString = ""; + boolean keepService = false; + if( fDstf != null) { + for (int i=0; i params = new HashMap(); + params.put("json", commJsString); + String responseJsString = conn.sendPost("json/plikiKollekto.php", params); + //Log.d("my_debug", "responseJsString: " + responseJsString); + + JSONObject responseJs = new JSONObject(responseJsString); // z tego czytam i tego nie modyfikuje + JSONObject responseJsCopy = new JSONObject(responseJsString); // tutaj robibie zmiany i później to zapisywane jest do pliku + + // obsługa pliku zawierającym statusy + String statJsString = readFile(prefs.getString("dir", "") + "/pliki_kollekto/statuses.json"); + JSONObject statJs = new JSONObject(statJsString); // z tego czytam + JSONObject statJsCopy = new JSONObject(statJsString);// w tym bede robic zmiany + + + + // parsowanie odpowiedzi z serwera, jeśli jest wpis downloading to znaczy że trzeba pobrać plik + Iterator pKeys = responseJs.keys(); + boolean limit = false; + boolean new_comm = false; + boolean save_stats = false; + while( pKeys.hasNext()){ + + String id_zlecenia = (String)pKeys.next(); + + JSONObject jZlecenie = responseJs.getJSONObject(id_zlecenia); + JSONObject jZlecenieCopy = responseJsCopy.getJSONObject(id_zlecenia); + + JSONObject statZl; + JSONObject statZlCopy = null; + if ( statJs.has(id_zlecenia) ) { + statZl = statJs.getJSONObject(id_zlecenia); + statZlCopy = statJsCopy.getJSONObject(id_zlecenia); + } + else { + statZl = new JSONObject(); + statJs.put(id_zlecenia, statZl); + } + + Iterator pKeys2 = jZlecenie.keys(); + while( pKeys2.hasNext()){ + Log.d("my_debug", "temp: "+responseJs.toString()); + String nazwa_pliku = (String)pKeys2.next(); + Log.d("my_debug", "temp, nazwa_pliku: "+nazwa_pliku); + String stat = jZlecenie.getString(nazwa_pliku); + // zmiany w pliku communication.json + if( "get".equals(stat) || "check".equals(stat) || "delete".equals(stat)) { + keepService = true; + } + if( "deleted".equals(stat) ) { + jZlecenieCopy.remove(nazwa_pliku); + } + if( "aborted".equals(stat) ) { + jZlecenieCopy.remove(nazwa_pliku); + } + if( "limit".equals(stat) ) { + limit = true; + jZlecenieCopy.remove(nazwa_pliku); + // todo: komunikat że osiągnięto limit + + statZlCopy.put(nazwa_pliku, "Do pobrania"); + // // + } + if( "downloading".equals(stat) ) { + // todo: pobierz zdjęcie fizycznie + String login = prefs.getString("user", ""); + conn.downloadFile("data/pliki_kollekto/"+login+"/"+id_zlecenia, prefs.getString("dir", "") + "/pliki_kollekto/"+id_zlecenia, nazwa_pliku); + jZlecenieCopy.remove(nazwa_pliku); + + //JSONObject statZl = statJs.getJSONObject(id_zlecenia); + statZlCopy.put(nazwa_pliku, "Pobrany"); + //DokumentyKollektoActivity.this.recreate(); + // // + } + + // zmiany w pliku statuses.json + // if( "downloading".equals(stat) ) { + // statJs + // } + } + + } + + if(limit) { + statJsCopy.put("limit", "true"); + } + else { + if ( statJs.has("limit") ) { + statJsCopy.remove("limit"); + } + } + + // / + + if( !statJs.equals(statJsCopy) ) { + writeFile(prefs.getString("dir", "") + "/pliki_kollekto/statuses.json", statJsCopy.toString()); + } + + + responseJsCopy = cleenResponseJs(responseJsCopy); + // Jesli po przetworzeniu odpowiedzi nadal cos w niej jest (znaczy ze trzeba stworzyc nowy plik z poloczeniem aby znowu byl wyslany(np. pozostal status check)) + Log.d("my_debug", "responseJsCopy: " + responseJsCopy.toString()+", respnseJsCopy.length: " + responseJsCopy.length() ); + if( responseJsCopy != null && !"".equals(responseJsCopy.toString().trim()) && responseJsCopy.length() > 0 ) { + Long time = (System.currentTimeMillis()); + String ts = Long.toString(time); + String newCommPath = prefs.getString("dir", "") + "/pliki_kollekto/comm_"+ts+".json"; + Log.d("my_debug", "tworze plik: " + newCommPath); + writeFile(newCommPath, responseJsCopy.toString()); + } + + // po przetworzeniu nalezy usunac wyslany plik komunikacyjny + File doneCommFile = new File(commPath); + Log.d("my_debug", "should delete: "+commPath); + if( doneCommFile.exists() ) { + Log.d("my_debug", "delete: "+commPath); + doneCommFile.delete(); + } + } + } + + + + if( !keepService ) { + stopService = true; + } + + } catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + } + + try { + int sleepTime = 10000; // 30s + Thread.sleep(sleepTime); + } catch (InterruptedException e) { + Log.d("DEDAL", "Interrupted", e); + } + } + + } + + private JSONObject cleenResponseJs(JSONObject responseJs) { + Iterator pKeys = responseJs.keys(); + boolean limit = false; + try { + while( pKeys.hasNext()){ + String id_zlecenia = (String)pKeys.next(); + JSONObject jZlecenie = responseJs.getJSONObject(id_zlecenia); + if( jZlecenie.length() == 0 ) { + responseJs.remove(id_zlecenia); + } + } + } catch (JSONException e) { + Log.e("DEDAL", "JSON", e); + } + return responseJs; + } + }); + t.start(); + + return super.onStartCommand(intent, flags, startId); + } + + @Override + public IBinder onBind(Intent arg0) { + // TODO Auto-generated method stub + return null; + } + + public void writeFile(String path, String content) { + DedalHelper.putFileContent(path, content); + } + + public String readFile(String path) { + + String content = ""; + try { + File myFile = new File(path); + if( myFile.isFile()){ + BufferedReader buf; + buf = new BufferedReader(new FileReader(myFile)); + content = buf.readLine(); + buf.close(); + } + } catch (IOException e) { + Log.e("DEDAL", "IO", e); + } + return content; + } + +} diff --git a/app/src/main/java/com/likesoft/mdedal/FragmentMainActivity.java b/app/src/main/java/com/likesoft/mdedal/FragmentMainActivity.java new file mode 100644 index 0000000..7d336cd --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/FragmentMainActivity.java @@ -0,0 +1,331 @@ +package com.likesoft.mdedal; + +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.graphics.Color; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.view.View; +import android.widget.Button; +import android.widget.FrameLayout; +import android.widget.HorizontalScrollView; +import android.widget.LinearLayout; +import android.widget.RelativeLayout; +import android.widget.ScrollView; + + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; + +/** + * Created by darek on 2016-01-10. + */ +public class FragmentMainActivity extends DedalActivity { + @Override + public View.OnClickListener getZapisz_zmiany(JSONObject jo, String typ) { + return null; + } + + boolean modified = false; + + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + // TODO Auto-generated method stub + super.onActivityResult(requestCode, resultCode, data); + if (data.hasExtra("json") && data.hasExtra("id")) { + // check if radio, find parent to set up value + try { + File dst = new File(prefs.getString("dir", "") + "/baza/" + m_id + ".mod"); + String sJson = DedalHelper.getFileContent(dst.getAbsolutePath()); + js = new JSONObject(sJson);//fs.read(buffer)); + + JSONObject jo = find_element_from_Array( js, data.getExtras().getString("id")); //todo check if not null + if( TYPE_RADIOBUTTON.equals(jo.getString(STRUCT_TYP_DANYCH)) ){ + // find parent + String parent = jo.getString("parent"); + Log.d("my_debug", "szukanie parenta" + parent);// + JSONObject jParent = find_element_from_Array(js, parent); + if( jParent!= null && TYPE_RADIOLISTA.equals(jParent.getString(STRUCT_TYP_DANYCH)) ){ + jParent.put(STRUCT_WARTOSC, jo.getInt("id_wiersz_szablonu")); + } + } + // stopAutozapis(); + // autoZapisStop = false; + mod_json_files(false); + + setModified(); + //MainActivity.this.reload(); + return; + + } catch (JSONException e) { + e.printStackTrace(); + } + + } + } + + @Override + protected void setModified() { + + if( !modified) { + llNaglowek.setBackgroundColor(Color.parseColor("#EBA0DD")); + Button bZapisz = new Button(this); + bZapisz.setText("Zapisz"); + bZapisz.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + if (modified) { + komunikat_obowiazkowe=""; + komunikat_walidacja=""; + zapiszZmiany(jo); + String komunikat = ""; + if( !komunikat_obowiazkowe.equals("") || !komunikat_walidacja.equals("") ) { + if( !komunikat_obowiazkowe.equals("") ) { + komunikat = res.getString(R.string.walid_pola_obowiazkowe) + ": \n"+komunikat_obowiazkowe + "\n"; + Log.d("my_debug", "Nie wypełniłeś pól obowiązkowych: " + komunikat); + } + if( !komunikat_walidacja.equals("") ) { + komunikat += "\n"+res.getString(R.string.walid_zle_wypelnione)+": \n"+komunikat_walidacja + "\n"; + } + } + if(komunikat!= ""){ + AlertDialog.Builder alertDialog = new AlertDialog.Builder(FragmentMainActivity.this); + alertDialog.setTitle( "Zapisywanie danych");//res.getString(R.string.zakanczanie_wizyty) ); //todo + alertDialog.setMessage(komunikat); + alertDialog.setPositiveButton("Anuluj", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int which) { + mod_json_files(false); + dialog.dismiss(); + } + }); + alertDialog.show(); + return; + }else { + modified = false; + saved = true; + } + } + finish(); + } + }); + llNaglowek.addView(bZapisz); + } + modified = true; + } + + @Override + protected void stopAutozapis() { + zapiszZmiany(jo); + } + + @Override + protected void mod_json_files(boolean mod_upload) { + + } + + @Override + protected void forceDoZapis(String key, String kod) { + + } + + String tmpFileName = ""; + //http://www.vogella.com/tutorials/AndroidIntent/article.html + @Override + public void onCreate(Bundle bundle) { + super.onCreate(bundle); + res = getResources(); + Context context = getApplicationContext(); + prefs = PreferenceManager.getDefaultSharedPreferences(context); + // setContentView(R.layout.activity_main); + + + + LinearLayout.LayoutParams linLayoutParam = new LinearLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); + + LinearLayout rl = new LinearLayout(this); + rl.setLayoutParams(linLayoutParam); + rl.setOrientation(LinearLayout.VERTICAL); +// rl.setBackgroundColor(Color.YELLOW); + + wyswietlNaglowek( rl ); +// if( bModified){ +// llNaglowek.setBackgroundColor(Color.parseColor("#EBA0DD")); +// } + + sw = new ScrollView(this); + rl.addView(sw); + + HorizontalScrollView hs = new HorizontalScrollView(this); + hs.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); + sw.addView(hs); + + LinearLayout llh = new LinearLayout(this); + int x = this.getWindow().getAttributes().width; + int xx = this.getWindowManager().getDefaultDisplay().getWidth(); //getRealSize(p); + Log.d("my_debug", "szerokość ekranu: "+ x+ ", real x: = " + xx); + llh.setLayoutParams( linLayoutParam); +// llh.setBackgroundColor(Color.RED); + hs.addView(llh); + + LinearLayout ll = new LinearLayout(this); + ll.setOrientation(LinearLayout.VERTICAL); + ll.setPadding(20, 5, 5, 5); //zmiana + ll.setLayoutParams( linLayoutParam); + ll.setMinimumWidth(xx); +// ll.setBackgroundColor(Color.GREEN); + llh.addView(ll); + + try { + Bundle extras = getIntent().getExtras(); + String filePathName = extras.getString("filePathName"); + tmpFileName = filePathName; + if( filePathName == null ) return; + + String sJson = DedalHelper.getFileContent(filePathName); + js = new JSONObject(sJson);//fs.read(buffer)); + + params = js.getJSONObject("param"); + m_id = params.getString("id_zlecenia"); + + String id = extras.getString("id"); + jo = find_element_from_Array(js, id); + find_powtarzalne(jo, 0); + boolean enabled = true; // + // enabled = Boolean.parseBoolean(extras.getString("enable")); + String sEnable = extras.getString("enable"); + if( !"true".equals(sEnable)){ + enabled = false; + } + + String status_interwencji = null; + if( getIntent().hasExtra("status_interwencji") ) { + status_interwencji = extras.getString("status_interwencji"); + } + + // wyswietlOpis(ll, jo); + wyswietlOpis(llNaglowek, jo); + + Log.d("my_debug", "Fragment, enabled"+enabled); + + JSONArray ja = jo.getJSONArray(STRUCT_CHILDS); + if (ja != null && ja.length() > 0) { + for (int i = 0; i < ja.length(); i++) { + wyswietlPole(ll, ja.getJSONObject(i), true, enabled, status_interwencji); + } + } + + } catch (JSONException e) { + e.printStackTrace(); + } + // TextView view = (TextView) findViewById(R.id.editTextHost); + // view.setText(inputString); + + // set LinearLayout as a root element of the screen + // setContentView(rl, linLayoutParam); + setContentView(rl); + + if( supportOnLoadReferences != null ) { + supporRadioRef(supportOnLoadReferences, View.GONE); + } + } + + JSONObject jo; + boolean saved = false; + + LinearLayout llNaglowek; + protected void wyswietlNaglowek(LinearLayout rl) { + LinearLayout ll = new LinearLayout(this); + llNaglowek = ll; + ll.setOrientation(LinearLayout.HORIZONTAL); + ll.setPadding(20, 5, 5, 5); + ll.setBackgroundColor(Color.parseColor("#9BF1F2")); + + HorizontalScrollView hw = new HorizontalScrollView(this); + rl.addView(hw); + hw.addView(ll); + + Button bAnuluj = new Button(this); + bAnuluj.setText("Anuluj"); + bAnuluj.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + modified = false; + finish(); + } + }); + llNaglowek.addView(bAnuluj); + } + + //@Override + public void onCreateFromResource(Bundle bundle) { + super.onCreate(bundle); + setContentView(R.layout.activity_main); + Bundle extras = getIntent().getExtras(); + String inputString = extras.getString("json"); + + + + try { + js = new JSONObject(inputString); + params = js.getJSONObject("param"); + m_id = params.getString("id_zlecenia"); + + String id = extras.getString("id"); + jo = find_element_from_Array(js, id); + find_powtarzalne(jo, 0); + LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayoutMain); + sw = (ScrollView)findViewById(R.id.scrollView1); + boolean enabled = true; // todo: przekazac? + wyswietlPole(ll, jo, true, enabled); + + + } catch (JSONException e) { + e.printStackTrace(); + } + + } + @Override + public void finish() { + Intent intent = new Intent(); +// EditText editText= (EditText) findViewById(R.id.returnValue); +// String string = editText.getText().toString(); + // String string = "aqq"; +// if( modified) { +// zapiszZmiany(jo); +// } + + if( saved ) { + // intent.putExtra("json", js.toString()); + try { + saveToModFile(js); + intent.putExtra("json","true"); + + } catch (IOException e) { + e.printStackTrace(); + } + + } + try { + intent.putExtra("id", jo.getString("id")); + intent.putExtra("status", "OK"); + intent.putExtra("tmpName",tmpFileName); + + } catch (JSONException e) { + e.printStackTrace(); + } + + setResult(RESULT_OK, intent); + super.finish(); + } + +} diff --git a/app/src/main/java/com/likesoft/mdedal/GPSTracker.java b/app/src/main/java/com/likesoft/mdedal/GPSTracker.java new file mode 100644 index 0000000..5a2876a --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/GPSTracker.java @@ -0,0 +1,252 @@ +package com.likesoft.mdedal; + +import java.util.Iterator; + +import android.Manifest; +import android.app.AlertDialog; +import android.app.Service; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.location.GpsSatellite; +import android.location.GpsStatus; +import android.location.GpsStatus.Listener; +import android.location.Location; +import android.location.LocationListener; +import android.location.LocationManager; +import android.os.Bundle; +import android.os.IBinder; +import android.provider.Settings; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +//import android.util.Log; + +public class GPSTracker extends Service implements LocationListener, Listener { + + private final Context mContext; + + // flag for GPS status + boolean isGPSEnabled = false; + + // flag for network status + boolean isNetworkEnabled = false; + + // flag for GPS status + boolean canGetLocation = false; + + Location location; // location + double latitude; // latitude + double longitude; // longitude + public int liczbaSatelitow = 0; + + // The minimum distance to change Updates in meters + private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 5;//10; // 10 meters + + // The minimum time between updates in milliseconds + private static final long MIN_TIME_BW_UPDATES = 1000 * 300;// 30sec // 60 * 1; // 1 minute + + // Declaring a Location Manager + protected LocationManager locationManager; + + public GPSTracker(Context context) { + this.mContext = context; + getLocation(); + } + + public Location getLocation() { + try { + locationManager = (LocationManager) mContext + .getSystemService(LOCATION_SERVICE); + + // Check runtime permissions for Android M+ + boolean hasFine = ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED; + boolean hasCoarse = ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED; + boolean hasLocation = hasFine || hasCoarse; + + // getting GPS status + isGPSEnabled = locationManager + .isProviderEnabled(LocationManager.GPS_PROVIDER); + + // getting network status + isNetworkEnabled = locationManager + .isProviderEnabled(LocationManager.NETWORK_PROVIDER); + + if (!isGPSEnabled && !isNetworkEnabled) { + // no network provider is enabled + } else { + this.canGetLocation = true; + // First get location from Network Provider + if (isNetworkEnabled && hasLocation) { + try { + locationManager.requestLocationUpdates( + LocationManager.NETWORK_PROVIDER, + MIN_TIME_BW_UPDATES, + MIN_DISTANCE_CHANGE_FOR_UPDATES, this); + } catch (SecurityException ignored) { } + if (locationManager != null) { + try { + location = locationManager + .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); + } catch (SecurityException ignored) { } + if (location != null) { + latitude = location.getLatitude(); + longitude = location.getLongitude(); + } + } + } + // GPS status listener (no permission required) + try { locationManager.addGpsStatusListener(this); } catch (Exception ignored) { } + + if (locationManager != null && hasLocation) { + try { + locationManager.requestLocationUpdates( + LocationManager.GPS_PROVIDER, + MIN_TIME_BW_UPDATES, + MIN_DISTANCE_CHANGE_FOR_UPDATES, this); + } catch (SecurityException ignored) { } + try { + location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); + } catch (SecurityException ignored) { } + } + // if GPS Enabled get lat/long using GPS Services + if (isGPSEnabled && location != null) { + latitude = location.getLatitude(); + longitude = location.getLongitude(); + } + } + + } catch (Exception e) { + e.printStackTrace(); + } + + return location; + } + + /** + * Stop using GPS listener + * Calling this function will stop using GPS in your app + * */ + public void stopUsingGPS() { + if (locationManager != null) { + locationManager.removeUpdates(GPSTracker.this); + } + } + + /** + * Function to get latitude + * */ + public double getLatitude() { + if (location != null) { + latitude = location.getLatitude(); + } + + // return latitude + return latitude; + } + + /** + * Function to get longitude + * */ + public double getLongitude() { + if (location != null) { + longitude = location.getLongitude(); + } + + // return longitude + return longitude; + } + + /** + * Function to check GPS/wifi enabled + * @return boolean + * */ + public boolean canGetLocation() { + return this.canGetLocation; + } + + /** + * Function to show settings alert dialog + * On pressing Settings button will lauch Settings Options + * */ + public void showSettingsAlert() { + AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); + + // Setting Dialog Title + alertDialog.setTitle("GPS jest wymagany"); + + // Setting Dialog Message + alertDialog.setMessage("GPS jest wyłączony. Czy chcesz go teraz włączyć?"); + + // On pressing Settings button + alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); + mContext.startActivity(intent); + } + }); + + // on pressing cancel button + alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + dialog.cancel(); + } + }); + + // Showing Alert Message + alertDialog.show(); + } + + @Override + public void onLocationChanged(Location location) { + this.location = location; + } + + @Override + public void onProviderDisabled(String provider) { + isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); + } + + @Override + public void onProviderEnabled(String provider) { + isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); + } + + @Override + public void onStatusChanged(String provider, int status, Bundle extras) { + } + + @Override + public IBinder onBind(Intent arg0) { + return null; + } + + @Override + public void onGpsStatusChanged(int event) { + // TODO Auto-generated method stub + //GpsStatus status = new GpsStatus(n); + // TODO Auto-generated method stub +// int permissionCheckGPS = ContextCompat.checkSelfPermission(getApplicationContext(), +// Manifest.permission.ACCESS_FINE_LOCATION); +// +// if (permissionCheckGPS == PackageManager.PERMISSION_GRANTED) { + Iterable gs = null; + try { + GpsStatus status = locationManager.getGpsStatus(null); + liczbaSatelitow= 0;//status.getMaxSatellites(); + if( status == null){ + return; + } + gs = status.getSatellites(); + } catch (SecurityException ignored) { return; } + if (gs == null) return; + Iterator it = gs.iterator(); + while( it.hasNext()){ + GpsSatellite g = it.next(); + liczbaSatelitow++; + } + +// } + } +} + diff --git a/app/src/main/java/com/likesoft/mdedal/KPActivity.java b/app/src/main/java/com/likesoft/mdedal/KPActivity.java new file mode 100644 index 0000000..dd8f473 --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/KPActivity.java @@ -0,0 +1,374 @@ +package com.likesoft.mdedal; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.HorizontalScrollView; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.Spinner; +import android.widget.TableLayout; +import android.widget.TableRow; +import android.widget.TextView; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +//import com.fasterxml.jackson.databind.ObjectMapper; +//import com.likesoft.mdedaltest.R; + +public class KPActivity extends Activity { + + private Map STATUS_NAMES = null; + //private LinearLayout lMain = null; + private SharedPreferences prefs = null; + private TableLayout tl = null; + private LinearLayout lCancelReason = null; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + STATUS_NAMES = new HashMap(); + STATUS_NAMES.put("aktywne", "Aktywne"); + STATUS_NAMES.put("zuzyte", "Zużyte"); + STATUS_NAMES.put("anulowane", "Anulowane"); + + prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); + + LinearLayout lMain = new LinearLayout(this); + lMain.setOrientation(LinearLayout.VERTICAL); + + ScrollView vScrollMain = new ScrollView(this); + HorizontalScrollView hScroll = new HorizontalScrollView(this); + vScrollMain.addView(hScroll); + hScroll.addView(lMain); + setContentView(vScrollMain); + + LinearLayout footer = new LinearLayout(this); + footer.setOrientation(LinearLayout.HORIZONTAL); + lMain.addView(footer); + + Button wyjdz = new Button(this); + wyjdz.setText("Wyjdź"); + wyjdz.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + finish(); + } + }); + footer.addView(wyjdz); + + //lMain.addView(getCancelReason()); + lCancelReason = new LinearLayout(this); + lCancelReason.setOrientation(LinearLayout.VERTICAL); + lMain.addView(lCancelReason); + + tl = new TableLayout(this); + lMain.addView(tl); + drawTable(); + + + } + + private void drawTable() { + + String KP_filename = prefs.getString("KP_filename", ""); + KP_filename = DedalHelper.getModOrJsonFileName(KP_filename); + + String KP_json = DedalHelper.getFileContent(KP_filename); + JSONArray KP_json_arr = null; + try { + KP_json_arr = new JSONArray(KP_json); + } catch (JSONException e) { + e.printStackTrace(); + } + + // obsługa nulla + if ( KP_json_arr != null ) { // obsługa nulla + + tl.removeAllViews(); + tl.setPadding(0, 15, 0, 0); + + TableRow tr_head = new TableRow(this); + tl.addView(tr_head); + + TextView twH = new TextView(this); + twH.setText("LP"); + twH.setPadding(5, 3, 5, 2); + tr_head.addView(twH); + + TextView twH2 = new TextView(this); + twH2.setText("KP"); + twH2.setPadding(5, 3, 5, 2); + tr_head.addView(twH2); + + TextView twH3 = new TextView(this); + twH3.setText("Status"); + twH3.setPadding(5, 3, 5, 2); + tr_head.addView(twH3); + + TextView twH4 = new TextView(this); + twH4.setText("Operacje"); + twH4.setPadding(5, 3, 5, 2); + tr_head.addView(twH4); + + for( int i = 0 ; i < KP_json_arr.length() ; i++ ) { + try { + JSONObject KP_obj = KP_json_arr.getJSONObject(i); + String status = KP_obj.getString("status"); + TableRow tr = new TableRow(this); + tr.setMinimumHeight(110); + tl.addView(tr); + + TextView tw = new TextView(this); + tw.setText(""+(i+1)); + tw.setPadding(5, 3, 5, 2); + tr.addView(tw); + + TextView tw2 = new TextView(this); + tw2.setText(KP_obj.getString("kp")); + tw2.setPadding(5, 3, 5, 2); + tr.addView(tw2); + + TextView tw3 = new TextView(this); + String status_text = STATUS_NAMES.get(status); + if( KP_obj.has("powod_anulowania") && !"".equals(KP_obj.getString("powod_anulowania")) && !"null".equals(KP_obj.getString("powod_anulowania")) ) { + status_text += "\nPowód: "+KP_obj.getString("powod_anulowania"); + } + tw3.setText(status_text); + tw3.setPadding(5, 3, 5, 2); + tr.addView(tw3); + + + + Button bt = new Button(this); + bt.setPadding(5, 3, 5, 2); + tr.addView(bt); + + if ("aktywne".equals(status) ) { + bt.setText("Anuluj"); + bt.setOnClickListener(new ShowCancelReasonOnClickListener(KP_json_arr, KP_obj)); + } + else if ("anulowane".equals(status) ) { + bt.setText("Przywróć"); + bt.setOnClickListener(new ActionOnClickListener(KP_json_arr, KP_obj, "restore")); + } + + } catch (JSONException e) { + e.printStackTrace(); + } + } + // obsługa nulla + } + else { + tl.removeAllViews(); + tl.setPadding(0, 15, 0, 0); + TextView label = new TextView(this); + label.setText("Błąd pobierania danych. Sprawdź połączenie z internetem."); + label.setPadding(5, 3, 5, 2); + tl.addView(label); + }// obsługa nulla + + } + + private class spinnerCancelOnItemSelectedListener implements AdapterView.OnItemSelectedListener { + + ArrayList items = null; + LinearLayout lInny = null; + EditText etInny = null; + + spinnerCancelOnItemSelectedListener(ArrayList items, LinearLayout lInny, EditText etInny) { + this.items = items; + this.lInny = lInny; + this.etInny = etInny; + } + + @Override + public void onItemSelected(AdapterView parentView, View selectedItemView, int position, long id) { + if( "inny".equals(items.get(position)) ) { + lInny.post(new Runnable() { + @Override + public void run() { + lInny.removeAllViews(); + TextView tv = new TextView(KPActivity.this); + tv.setText("Wpisz: "); + lInny.addView(tv); + lInny.addView(etInny); + } + }); + } + else { + lInny.post(new Runnable() { + @Override + public void run() { + lInny.removeAllViews(); + } + }); + } + } + + @Override + public void onNothingSelected(AdapterView parentView) { + + } + + } + + private class ShowCancelReasonOnClickListener implements OnClickListener { + JSONObject kp_obj = null; + JSONArray kp_arr = null; + + ShowCancelReasonOnClickListener(JSONArray kp_arr, JSONObject kp_obj) { + this.kp_obj = kp_obj; + this.kp_arr = kp_arr; + } + + @Override + public void onClick(View v) { + + lCancelReason.post(new Runnable() { + @Override + public void run() { + lCancelReason.removeAllViews(); + lCancelReason.addView(getCancelReason(kp_arr, kp_obj)); + } + }); + } + } + private class ActionOnClickListener implements OnClickListener { + + JSONObject kp_obj = null; + JSONArray kp_arr = null; + String action = "cancel"; // 'cancel' | 'restore' + Spinner cancelSpin = null; + EditText etInny = null; + + ActionOnClickListener(JSONArray kp_arr, JSONObject kp_obj, String action) { + this.kp_obj = kp_obj; + this.kp_arr = kp_arr; + this.action = action; + } + + ActionOnClickListener(JSONArray kp_arr, JSONObject kp_obj, String action, Spinner cancelSpin, EditText etInny) { + this.kp_obj = kp_obj; + this.kp_arr = kp_arr; + this.action = action; + this.cancelSpin = cancelSpin; + this.etInny = etInny; + } + + @Override + public void onClick(View v) { + try { + if ("cancel".equals(action) ) { + kp_obj.put("status", "anulowane"); + if( cancelSpin != null ) { + String powod = cancelSpin.getSelectedItem().toString(); + if( etInny != null && !"".equals(etInny.getText().toString().trim()) ) { + powod += ": " + etInny.getText(); + } + kp_obj.put("powod_anulowania", powod); + } + } + else if("restore".equals(action)) { + kp_obj.put("status", "aktywne"); + kp_obj.put("powod_anulowania", ""); + } + + String KP_filename = prefs.getString("KP_filename", ""); + KP_filename = KP_filename.replace(".json", ".mod"); + + // copy to .mod + DedalHelper.putFileContent(KP_filename, kp_arr.toString()); + + //copy to upload folder + String dir_upload = prefs.getString("dir", ""); + dir_upload += "/upload_kp"; + File fup = new File(dir_upload); + if( !fup.isDirectory()){ + fup.mkdirs(); + } + //String upload_file_name = KP_filename.replace(".json", ""); + String upload_file_name = "kp_"+(new Date()).getTime() + ".mod"; + DedalHelper.putFileContent(dir_upload + "/" + upload_file_name, kp_arr.toString()); + + drawTable(); + lCancelReason.post(new Runnable() { + @Override + public void run() { + lCancelReason.removeAllViews(); + } + }); + + //wystartuj/obudź serwis + Context context = getApplicationContext(); + Intent service = new Intent(context, DedalService.class); + context.startService(service); + + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + + private LinearLayout getCancelReason(JSONArray KP_json_arr, JSONObject KP_obj){ + LinearLayout lCancelReason = new LinearLayout(this); + lCancelReason.setOrientation(LinearLayout.VERTICAL); + //lMain.addView(lCancelReason); + + TextView tv = new TextView(this); + tv.setText("Powód: "); + lCancelReason.addView(tv); + + Spinner spinCancelReason = new Spinner(this); + lCancelReason.addView(spinCancelReason); + + ArrayList items = new ArrayList(); + items.add("anulowany"); + //items.add("zagubiony"); + //items.add("zniszczony"); + //items.add("inny"); + + ArrayAdapter aa = new ArrayAdapter( + this, + android.R.layout.simple_spinner_item, + items.toArray()); + + aa.setDropDownViewResource( + android.R.layout.simple_spinner_dropdown_item); + + LinearLayout lInny = new LinearLayout(this); + lCancelReason.addView(lInny); + + EditText etInny = new EditText(this); + + //spinCancelReason.setOnItemSelectedListener(new CustomOnItemSelectedListener()); + spinCancelReason.setOnItemSelectedListener(new spinnerCancelOnItemSelectedListener(items, lInny, etInny)); + spinCancelReason.setAdapter(aa); + + Button bAnuluj = new Button(this); + bAnuluj.setText("Anuluj KP"); + bAnuluj.setOnClickListener(new ActionOnClickListener(KP_json_arr, KP_obj, "cancel", spinCancelReason, etInny)); + + lCancelReason.addView(bAnuluj); + + return lCancelReason; + } +} \ No newline at end of file diff --git a/app/src/main/java/com/likesoft/mdedal/KPWplatyActivity.java b/app/src/main/java/com/likesoft/mdedal/KPWplatyActivity.java new file mode 100644 index 0000000..bc047b7 --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/KPWplatyActivity.java @@ -0,0 +1,267 @@ +package com.likesoft.mdedal; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TableLayout; +import android.widget.TableRow; +import android.widget.TextView; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.util.Date; +import java.util.Iterator; + + +public class KPWplatyActivity extends Activity { + + private SharedPreferences prefs = null; + //private LinearLayout lMain = null; + private LinearLayout lContent = null; + private JSONObject KPWplaty_json = null; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + + prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); + + LinearLayout lMain = new LinearLayout(this); + lMain.setOrientation(LinearLayout.VERTICAL); + //lMain.setPadding(50, 15, 15, 15); + + ScrollView vScroll = new ScrollView(this); + vScroll.addView(lMain); + + setContentView(vScroll); + + LinearLayout footer = new LinearLayout(this); + footer.setOrientation(LinearLayout.HORIZONTAL); + lMain.addView(footer); + + Button wyjdz = new Button(this); + wyjdz.setText("Wyjdź"); + wyjdz.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + finish(); + } + }); + footer.addView(wyjdz); + + // REFRESH BUTTON + RefreshLayoutAndThread rlat = new RefreshLayoutAndThread(this) { + @Override + protected void whenThreadNeedToReaoad() { + + } + + @Override + protected void setLastGPSInfo_abstr() { + + } + + @Override + protected void onServiceFinisz() { + drawTable(); + } + }; + LinearLayout refreshLayout = rlat.getRefreshLayout(); + refreshLayout.setPadding(10, 0, 0, 0); + TextView textUpload = rlat.getTextUpload(); + footer.addView(textUpload); + rlat.setLastUpdateInfo(); + rlat.start(); + footer.addView(refreshLayout); + + lContent = new LinearLayout(this); + lContent.setOrientation(LinearLayout.VERTICAL); + lMain.addView(lContent); + + drawTable(); + } + + private void drawTable() { + String KPWplaty_filename = prefs.getString("KPWplaty_filename", ""); + KPWplaty_filename = DedalHelper.getModOrJsonFileName(KPWplaty_filename); + + String KPWplaty_json_string = DedalHelper.getFileContent(KPWplaty_filename); + try { + KPWplaty_json = new JSONObject(KPWplaty_json_string); + } catch (JSONException e) { + e.printStackTrace(); + } + + lContent.removeAllViews(); + lContent.setPadding(0, 15, 0, 0); + + if( KPWplaty_json == null ) return; + + Iterator k = KPWplaty_json.keys(); + while (k.hasNext()) { + String id_fundusz = (String) k.next(); + try { + JSONObject fundusz_obj = KPWplaty_json.getJSONObject(id_fundusz); + LinearLayout funduszLayout = new LinearLayout(this); + funduszLayout.setOrientation(LinearLayout.VERTICAL); + lContent.addView(funduszLayout); + + TextView titleTv = new TextView(this); + titleTv.setText("" + fundusz_obj.getString("nazwa_funduszu") + ", nr karty: " + fundusz_obj.getString("nr_karty")); + titleTv.setTextSize(30); + funduszLayout.addView(titleTv); + + TableLayout tl = new TableLayout(this); + funduszLayout.addView(tl); + JSONArray wplatyJson = fundusz_obj.getJSONArray("wplaty"); + if( wplatyJson != null && wplatyJson.length() > 0 ) { + // header + TableRow tr_head = new TableRow(this); + tl.addView(tr_head); + + TextView twH = new TextView(this); + twH.setText("LP"); + twH.setPadding(5, 3, 5, 2); + tr_head.addView(twH); + + /*TextView twH2 = new TextView(this); + twH2.setText("Zlecenie"); + twH2.setPadding(5, 3, 5, 2); + tr_head.addView(twH2);*/ + + TextView twH1 = new TextView(this); + twH1.setText("KP"); + twH1.setPadding(5, 3, 5, 2); + tr_head.addView(twH1); + + TextView twH2 = new TextView(this); + twH2.setText("Nr sprawy"); + twH2.setPadding(5, 3, 5, 2); + tr_head.addView(twH2); + + + TextView twH3 = new TextView(this); + twH3.setText("Kwota"); + twH3.setPadding(5, 3, 5, 2); + tr_head.addView(twH3); + + for( int i = 0 ; i < wplatyJson.length() ; i++ ) { + JSONObject wplataJson = wplatyJson.getJSONObject(i); + + TableRow tr = new TableRow(this); + tl.addView(tr); + + TextView tw = new TextView(this); + tw.setText(""+(i+1)); + tw.setPadding(5, 3, 5, 2); + tr.addView(tw); + + /*TextView tw2 = new TextView(this); + tw2.setText(wplataJson.getString("id_zlecenia")); + tw2.setPadding(5, 3, 5, 2); + tr.addView(tw2);*/ + + TextView tw1 = new TextView(this); + tw1.setText(wplataJson.getString("kp")); + tw1.setPadding(5, 3, 5, 2); + tr.addView(tw1); + + TextView tw2 = new TextView(this); + tw2.setText(wplataJson.getString("nr_sprawy")); + tw2.setPadding(5, 3, 5, 2); + tr.addView(tw2); + + TextView tw3 = new TextView(this); + tw3.setText(wplataJson.getString("kwota")); + tw3.setPadding(5, 3, 5, 2); + tr.addView(tw3); + } + + TableRow tr = new TableRow(this); + tl.addView(tr); + + TextView sumaTvLabel = new TextView(this); + sumaTvLabel.setText("Suma"); + sumaTvLabel.setTextSize(30); + sumaTvLabel.setPadding(5, 3, 5, 2); + tr.addView(sumaTvLabel); + + TableRow.LayoutParams params = (TableRow.LayoutParams) sumaTvLabel.getLayoutParams(); + params.span = 2; //amount of columns you will span + sumaTvLabel.setLayoutParams(params); + + TextView sumaTv = new TextView(this); + sumaTv.setText(fundusz_obj.getString("suma")+" zł"); + sumaTv.setTextSize(30); + sumaTv.setPadding(5, 3, 5, 2); + tr.addView(sumaTv); + } + + if ( fundusz_obj.getString("nr_karty") != null && fundusz_obj.getString("nr_karty").length() > 0 ) { //Mateusz - no display if don't have card + Button bWplacam = new Button(this); + bWplacam.setText("Wpłacam"); + bWplacam.setOnClickListener(new WplacamOnClickListener(id_fundusz)); + funduszLayout.addView(bWplacam); + } + + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + + private class WplacamOnClickListener implements OnClickListener { + + String id_fundusz = null; + + WplacamOnClickListener(String id_fundusz) { + this.id_fundusz = id_fundusz; + } + + @Override + public void onClick(View v) { + //copy to upload folder + String dir_upload = prefs.getString("dir", ""); + dir_upload += "/upload_kp_wplaty"; + File fup = new File(dir_upload); + if( !fup.isDirectory()){ + fup.mkdirs(); + } + + //String upload_file_name = KP_filename.replace(".json", ""); + String upload_file_name = "kp_wplaty_"+(new Date()).getTime() + ".mod"; + + JSONArray ids_wplat = new JSONArray(); + try { + JSONObject fundusz_obj = KPWplaty_json.getJSONObject(id_fundusz); + JSONArray wplatyJson = fundusz_obj.getJSONArray("wplaty"); + for( int i = 0 ; i < wplatyJson.length() ; i++ ) { + JSONObject wplataJson = wplatyJson.getJSONObject(i); + ids_wplat.put(wplataJson.get("id")); + } + + DedalHelper.putFileContent(dir_upload + "/" + upload_file_name, ids_wplat.toString()); + } catch (JSONException e) { + e.printStackTrace(); + } + + + //wystartuj/obudź serwis + Context context = getApplicationContext(); + Intent service = new Intent(context, DedalService.class); + context.startService(service); + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/likesoft/mdedal/ListActivity.java b/app/src/main/java/com/likesoft/mdedal/ListActivity.java new file mode 100644 index 0000000..64dbe4c --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/ListActivity.java @@ -0,0 +1,3473 @@ +package com.likesoft.mdedal; + +import android.Manifest; +import android.app.Activity; +import android.app.AlertDialog; +import android.content.ClipData; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.SharedPreferences.Editor; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.content.pm.PackageManager.NameNotFoundException; +import android.content.res.Configuration; +import android.content.res.Resources; +import android.graphics.Bitmap; +import android.graphics.Color; +import android.graphics.Point; +import android.graphics.drawable.BitmapDrawable; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.os.Environment; +import android.os.StrictMode; +import android.preference.PreferenceManager; +import android.provider.Settings; +import androidx.annotation.NonNull; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +import android.text.Editable; +import android.text.TextWatcher; +import android.util.SparseArray; +import android.view.DragEvent; +import android.view.Gravity; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.View.OnDragListener; +import android.view.View.OnTouchListener; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemSelectedListener; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.EditText; +import android.widget.HorizontalScrollView; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.RadioButton; +import android.widget.RadioGroup; +import android.widget.ScrollView; +import android.widget.SearchView; +import android.widget.SearchView.OnQueryTextListener; +import android.widget.Spinner; +import android.widget.TableLayout; +import android.widget.TableRow; +import android.widget.TextView; +import android.widget.Toast; +import android.widget.ToggleButton; + +import com.likesoft.mdedal.gui.MTextView; +//import com.likesoft.mdedaltest.R; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintWriter; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +//import android.util.Log; +//import com.likesoft.mdedaltest.PreferActivityTest; + +public class ListActivity extends Activity { + private static final int REQUEST_READ_PHONE_STATE = 5001; + private static final int REQUEST_ACCESS_FINE_LOCATION = 5002; + private static final int REQUEST_POST_NOTIFICATIONS = 5003; + private static final int REQUEST_APP_PERMISSIONS = 4000; + private static final int REQUEST_MANAGE_ALL_FILES = 4001; + + protected Class getMainActivity() { + return MainActivity.class; + } + protected Class getTableHeadersActivity() { + return TableHeadersActivity.class; + } + protected Class getCalendarActivity() { + return CalendarActivity.class; + } + protected Class getKPActivity() { + return KPActivity.class; + } + protected Class getKPWplatyActivity() { + return KPWplatyActivity.class; + } + + @Override + public void onConfigurationChanged(Configuration newConfig) { + // TODO Auto-generated method stub + super.onConfigurationChanged(newConfig); + Context context = getApplicationContext(); + Log.d(LOG, "onConfigurationChanged: " + newConfig.toString()); + Intent intent = getIntent(); + intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); + finish(); + startActivity(intent); + } + + public final static String LOG = "ListActivity"; + String sf = null; + ArrayList names = null; + + public static String readFile(InputStream in) throws IOException { + StringBuffer sb = new StringBuffer(); + byte buffer[] = new byte[1000]; + int s = 0; + while ((s = in.read(buffer)) > 0) { + String st =new String(buffer, 0, s); + sb.append(st); + } + in.close(); + return sb.toString(); + } + +// String hostPath = "http://javax.pl/dedal/demo"; +// String hostPath = "http://192.168.1.23/svn/dedal/src"; + SharedPreferences prefs; + + private final class Wyswietl_linie_konca_Thread implements Runnable { + TableLayout tl; + public Wyswietl_linie_konca_Thread(TableLayout _tl) { + tl = _tl; + } + @Override + public void run() { + + // TODO Auto-generated method stub + wyswietl_linie_konca(tl); + } +} + + private final class MyWiersTRThread implements Runnable { + TableLayout tl; JSONArray jKolumny; + JSONObject jZlecenie; int i; + public MyWiersTRThread(TableLayout _tl, JSONArray _jKolumny, + JSONObject _jZlecenie, int _i) { + tl = _tl; + jKolumny = _jKolumny; + jZlecenie = _jZlecenie; + i = _i; + } + @Override + public void run() { + // TODO Auto-generated method stub + try { + wyswietl_wierszTR(tl, jKolumny, jZlecenie, i); + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } +} + + private final class MyTabelaThread implements Runnable { + + JSONArray jKolumny; TableLayout tl; + ArrayList aM; + public MyTabelaThread(JSONArray _jKolumny, TableLayout _tl, + ArrayList _aM) { + + jKolumny = _jKolumny; + tl = _tl; + aM = _aM; + } + @Override + public void run() { + // TODO Auto-generated method stub + try { + wyswietl_tabele_zlecen(jKolumny, tl, aM); + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } +} + +// private final class MyWyswietlLinieThread implements Runnable { +// JSONArray Kolumny; +// TableRow tr; +// JSONObject jZlecenie; +// public MyWyswietlLinieThread(JSONArray _Kolumny, TableRow _tr, +// JSONObject _jZlecenie) { +// Kolumny = _Kolumny; +// tr = _tr; +// jZlecenie = _jZlecenie; +// } +// +// @Override +// public void run() { +// // TODO Auto-generated method stub +// try { +// wyswietlLinie(Kolumny, tr, jZlecenie); +// } catch (JSONException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } +// } +//} + + private final class EditFolderOnClickListener implements OnClickListener { + @SuppressWarnings("deprecation") + @Override + public void onClick(View v) { + String title = null; + if( id_folder > 0 ) { + int pos = findPosFolder(id_folder); + String nazwa_folderu = folderNazwy.get(pos); + title = "Edycja folderu: " + nazwa_folderu; + } + else { + title = "Dodawanie nowego folderu"; + } + //String nazwa_folderu = "costam"; + + AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ListActivity.this); + AlertDialog alertDialog = alertDialogBuilder.create(); + alertDialog.setTitle( title ); + LinearLayout ll = new LinearLayout(ListActivity.this); + ll.setOrientation(LinearLayout.VERTICAL); + + // Edycja folderu + if( id_folder > 0 ) { + LinearLayout ll_edit_folder = new LinearLayout(ListActivity.this); + ll_edit_folder.setOrientation(LinearLayout.HORIZONTAL); + TextView tw1 = new TextView(ListActivity.this); + tw1.setText("Nowa nazwa folderu:"); + EditText et = new EditText(ListActivity.this); + et.setMinWidth(60); + maxId++; + et.setId(maxId); + Log.d("my_debug", "przed id: "+et.getId()); + ll_edit_folder.addView(tw1); + ll_edit_folder.addView(et); + Button b_edit_folder = new Button(ListActivity.this); + b_edit_folder.setText("OK"); + b_edit_folder.setOnClickListener(new Edit_folder_onlick(et, alertDialog)); + ll_edit_folder.addView(b_edit_folder); + + Button b_delete_folder = new Button(ListActivity.this); + b_delete_folder.setText("Usuń folder"); + b_delete_folder.setOnClickListener(new Delete_folder_onlick(et, alertDialog)); + ll_edit_folder.addView(b_delete_folder); + + ll.addView(ll_edit_folder); + } + ///// + + // Nowy folder + LinearLayout ll_new_folder = new LinearLayout(ListActivity.this); + ll_new_folder.setOrientation(LinearLayout.HORIZONTAL); + TextView tw1 = new TextView(ListActivity.this); + tw1.setText("Dodaj nowy folder:"); + EditText et = new EditText(ListActivity.this); + et.setMinWidth(60); + maxId++; + et.setId(maxId); + Log.d("my_debug", "przed id: "+et.getId()); + ll_new_folder.addView(tw1); + ll_new_folder.addView(et); + Button b_new_folder = new Button(ListActivity.this); + b_new_folder.setText("OK"); + b_new_folder.setOnClickListener(new New_folder_onlick(et, alertDialog)); + ll_new_folder.addView(b_new_folder); + ///// + + ll.addView(ll_new_folder); + alertDialog.setView(ll); + //alertDialog.setPositiveButton("OK", new New_folder_onlick(et)); + alertDialog.setButton("Anuluj", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int which) { + //mod_json_files(false); + dialog.dismiss(); + } + }); + alertDialog.show(); + } + + private int findPosFolder(int id_folder) { + int pos = 0; + for( pos = 0 ; pos < folderIds.size() ; pos++ ) { + if( folderIds.get(pos) == id_folder ) { + break; + } + } + return pos; + + } + } + + private final class MyComparator_sortInFolder implements + Comparator { + + JSONArray jkolejnosc_zlecen; + + public MyComparator_sortInFolder(JSONArray jkolejnosc_zlecen) { + this.jkolejnosc_zlecen = jkolejnosc_zlecen; + } + + @Override + public int compare(JSONObject lhs, JSONObject rhs) { + // TODO Auto-generated method stub + try { + //Log.d("my_debug", "trara: "+ lhs.getString("id_zlecenia")+" | "+rhs.getString("id_zlecenia")); + //Log.d("my_debug", "trara: "+ find_kol(lhs.getString("id_zlecenia"))+" | "+find_kol(lhs.getString("id_zlecenia"))); + if( find_kol(lhs.getString("id_zlecenia")) < find_kol(rhs.getString("id_zlecenia")) ) { + return -1; + } + else { + return 1; + } + //return lhs.getString(sortCol).compareTo(rhs.getString(sortCol)) *bSortASC; + } catch (JSONException e) { + } + return 0; + } + + private int find_kol(String id_zlecenia) { + int i = 0; + for( i = 0 ; i < jkolejnosc_zlecen.length() ; i++) { + try { + //Log.d("my_debug", "oj "+i+": |"+jkolejnosc_zlecen.getString(i)+"|"+id_zlecenia+"|"); + if( jkolejnosc_zlecen.getString(i).equals(id_zlecenia)) { + break; + } + } catch (JSONException e) { + // TODO Auto-generated catch block + Log.e(LOG, "", e); + } + } + return i; + } + } + +private final class Delete_folder_onlick implements OnClickListener { + + //int id; + EditText et; + AlertDialog alertDialog; + + public Delete_folder_onlick(EditText et, AlertDialog alertDialog) { + this.et = et; + this.alertDialog = alertDialog; + } + + @Override + public void onClick(View arg0) { + if( et != null ) { + String nazwa = et.getText().toString(); + + try { + JSONObject mainJs = new JSONObject(); + JSONObject contentJs = new JSONObject(); + contentJs.put("id_folder", id_folder); + //contentJs.put("operation", "delete"); + //contentJs.put("id_folder", id_folder_gui); + mainJs.put("delete_folder", contentJs); + + changeIdFolderInListaProfil(id_folder, 0); + removeFolderFromListaProfil(id_folder); + + Date d = new Date(); + String genName = "folder_"+d.getTime() + ".mod"; + File dstDir = new File(prefs.getString("dir", "") + "/upload_folders_mod"); + if( !dstDir.isDirectory()){ dstDir.mkdirs(); } + DedalHelper.putFileContent(prefs.getString("dir", "") + "/upload_folders_mod/" + genName, mainJs.toString()); + + // wystartuj/obudz serwis + Context context = getApplicationContext(); + Intent service = new Intent(context, DedalService.class); + context.startService(service); + + //((DialogInterface)alertDialog).dismiss(); + alertDialog.dismiss(); + } catch (JSONException e) { + // TODO Auto-generated catch block + Log.e(LOG, "", e); + } + } + else { + Log.d("my_debug", "et jest null");//, id: "+id); + } + } + } + + private final class Edit_folder_onlick implements OnClickListener { + + //int id; + EditText et; + AlertDialog alertDialog; + + public Edit_folder_onlick(EditText et, AlertDialog alertDialog) { + this.et = et; + this.alertDialog = alertDialog; + } + + @Override + public void onClick(View arg0) { + if( et != null ) { + String nazwa = et.getText().toString(); + + try { + JSONObject mainJs = new JSONObject(); + JSONObject contentJs = new JSONObject(); + contentJs.put("nazwa", nazwa); + contentJs.put("id_folder", id_folder); + //contentJs.put("operation", "edit"); + //contentJs.put("id_folder", id_folder_gui); + mainJs.put("edit_folder", contentJs); + + changeFolderNameInListaProfil(id_folder, nazwa); + + Date d = new Date(); + String genName = "folder_"+d.getTime() + ".mod"; + File dstDir = new File(prefs.getString("dir", "") + "/upload_folders_mod"); + if( !dstDir.isDirectory()){ dstDir.mkdirs(); } + + DedalHelper.putFileContent(prefs.getString("dir", "") + "/upload_folders_mod/" + genName, mainJs.toString()); + + // wystartuj/obudz serwis + Context context = getApplicationContext(); + Intent service = new Intent(context, DedalService.class); + context.startService(service); + + //((DialogInterface)alertDialog).dismiss(); + alertDialog.dismiss(); + } catch (JSONException e) { + Log.e(LOG, "", e); + } + } + else { + Log.d("my_debug", "et jest null");//, id: "+id); + } + } + } + + private final class New_folder_onlick implements OnClickListener { + + //int id; + EditText et; + AlertDialog alertDialog; + + public New_folder_onlick(EditText et, AlertDialog alertDialog) { + this.et = et; + this.alertDialog = alertDialog; + } + + @Override + public void onClick(View arg0) { + if( et != null ) { + String nazwa = et.getText().toString(); + + try { + JSONObject mainJs = new JSONObject(); + JSONObject contentJs = new JSONObject(); + contentJs.put("nazwa", nazwa); + //contentJs.put("operation", "new"); + //contentJs.put("id_folder", id_folder_gui); + mainJs.put("new_folder", contentJs); + + addFolderInListaProfil( nazwa ); + + Date d = new Date(); + String genName = "folder_"+d.getTime() + ".mod"; + File dstDir = new File(prefs.getString("dir", "") + "/upload_folders_mod"); + if( !dstDir.isDirectory()){ dstDir.mkdirs(); } + + DedalHelper.putFileContent(prefs.getString("dir", "") + "/upload_folders_mod/" + genName, mainJs.toString()); + + // wystartuj/obudz serwis + Context context = getApplicationContext(); + Intent service = new Intent(context, DedalService.class); + context.startService(service); + + //((DialogInterface)alertDialog).dismiss(); + alertDialog.dismiss(); + } catch (JSONException e) { + Log.e(LOG, "", e); + } + } + else { + Log.d("my_debug", "et jest null");//, id: "+id); + } + } + } + +// public class MyClickListener implements OnClickListener{ +// String name = ""; +// public MyClickListener(String n){ +// super(); +// name = n; +// } +// +// public void onClick(View v) { +// // TODO Auto-generated method stub +// +// +// Intent intent = new Intent(ListActivity.this, +// getMainActivity()); +// File f = new File(sf + "/" + name); +// Uri u = Uri.fromFile(f); +// intent.setData(u); +// startActivity(intent); +// } +// } + + public class CustomOnItemSelectedListener implements OnItemSelectedListener { + + public void onItemSelected(AdapterView parent, View view, int pos, + long id) { + + Toast.makeText(parent.getContext(), + "Wybrano profil : " + parent.getItemAtPosition(pos).toString(), + Toast.LENGTH_LONG).show(); + + id_profilu = profileIds.get(pos); + //todo filtry: narazie zakomentowane + //filterItems = new ArrayList(); // czyszczenie filtra wyboru. + + //JSONObject jProfil; + try { + jProfil = jProfiles.getJSONObject(id_profilu); + curPage = 0; + wyswietlListe(); + } catch (JSONException e) { + Log.e(LOG, "", e); + } + + } + @Override + public void onNothingSelected(AdapterView arg0) { + // TODO Auto-generated method stub + } + } + + public class CustomOnFolderSelectedListener implements OnItemSelectedListener { + + public void onItemSelected(AdapterView parent, View view, int pos, + long id) { + + if(id_folder != folderIds.get(pos)) { + Log.d("my_debug", "onitemselected, id_folder old: "+id_folder+", id_folder new: "+folderIds.get(pos)); + id_folder = folderIds.get(pos); + curPage = 0; + wyswietlListe(); + } + + } + @Override + public void onNothingSelected(AdapterView arg0) { + // TODO Auto-generated method stub + } + } + + private void addFolderInListaProfil( String nazwa ) { + try { + File dLista = new File(prefs.getString("dir", "") + "/baza/lista.profil"); + if( dLista.isFile()){ + String sJson = DedalHelper.getFileContent(dLista.getAbsolutePath()); + JSONObject jFile = new JSONObject(sJson); + + int max_id_folder = 0; + for(int i = 0 ; i < folderIds.size(); i++) { + if ( folderIds.get(i) > max_id_folder ) { + max_id_folder = folderIds.get(i); + } + } + int id_folder_new = max_id_folder + 1; + + Log.d("my_debug", "jfile folder: "+jFile.getString("foldery")); + + JSONObject jFolders; + + if( !jFile.has("foldery") || "null".equals(jFile.getString("foldery")) ) { + //Log.d("my_debug", "new json"); + jFolders = new JSONObject(); + jFile.put("foldery", jFolders); + } + else { + + jFolders = jFile.getJSONObject("foldery"); + //Log.d("my_debug", "exist json, "+jFolders.toString()); + } + JSONObject jFolder = new JSONObject(); + jFolder.put("id_folder", id_folder_new); + jFolder.put("nazwa", nazwa); + + jFolders.put(Integer.toString(id_folder_new), jFolder); + + DedalHelper.putFileContent(prefs.getString("dir", "") + "/baza/lista.profil", jFile.toString()); + } + } catch (JSONException e) { + Log.e(LOG, "", e); + } + } + + private void changeFolderNameInListaProfil(int id_folder, String nazwa) { + try { + File dLista = new File(prefs.getString("dir", "") + "/baza/lista.profil"); + if( dLista.isFile()){ + String sJson = DedalHelper.getFileContent(dLista.getAbsolutePath()); + JSONObject jFile = new JSONObject(sJson); + + JSONObject jFolders = jFile.getJSONObject("foldery"); + JSONObject jFolder = jFolders.getJSONObject(Integer.toString(id_folder)); + jFolder.put("nazwa", nazwa); + + DedalHelper.putFileContent(prefs.getString("dir", "") + "/baza/lista.profil", jFile.toString()); + } + } catch (JSONException e) { + Log.e(LOG, "", e); + } + } + + private void removeFolderFromListaProfil(int id_folder) { + try { + File dLista = new File(prefs.getString("dir", "") + "/baza/lista.profil"); + if( dLista.isFile()){ + String sJson = DedalHelper.getFileContent(dLista.getAbsolutePath()); + JSONObject jFile = new JSONObject(sJson); + JSONObject jFolders = jFile.getJSONObject("foldery"); + jFolders.remove(Integer.toString(id_folder)); + DedalHelper.putFileContent(prefs.getString("dir", "") + "/baza/lista.profil", jFile.toString()); + } + } catch (JSONException e) { + Log.e(LOG, "", e); + } + } + + private void changeIdFolderInListaProfil(int id_folder_old, int id_folder_new) { + try { + File dLista = new File(prefs.getString("dir", "") + "/baza/lista.profil"); + if( dLista.isFile()){ + + String sJson = DedalHelper.getFileContent(dLista.getAbsolutePath()); + JSONObject jFile = new JSONObject(sJson); + + JSONObject jProfiles = jFile.getJSONObject("profile"); + Iterator pKeys = jProfiles.keys(); + //Boolean break_ = false; + + while( pKeys.hasNext()){ + String idProfilu = (String)pKeys.next(); + JSONObject jProfil = jProfiles.getJSONObject(idProfilu); + JSONObject jZlecenia = jProfil.getJSONObject("zlecenia"); + Iterator pKeys2 = jZlecenia.keys(); + while( pKeys2.hasNext() ){ + String id_zlecenia = (String)pKeys2.next(); + JSONObject jZlecenie = jZlecenia.getJSONObject(id_zlecenia); + if(jZlecenie.has("id_folder") && !jZlecenie.getString("id_folder").equals("null") && jZlecenie.getInt("id_folder") == id_folder_old) { + if(id_folder_new == 0) { + jZlecenie.put("id_folder", "null"); + } + else { + jZlecenie.put("id_folder", id_folder_new); + } + } + } + } + + DedalHelper.putFileContent(prefs.getString("dir", "") + "/baza/lista.profil", jFile.toString()); + } + } catch (JSONException e) { + Log.e(LOG, "", e); + } + } + + public class ChangeZlecenieFolderSelectedListener implements + OnItemSelectedListener { + + private JSONObject jZlecenie; + + public ChangeZlecenieFolderSelectedListener(JSONObject jZlecenie){ + this.jZlecenie = jZlecenie; + } + + + @Override + public void onItemSelected(AdapterView parent, View view, int pos, + long id) { + if( folderIdsForOrders.get(pos) != null ) { + + //Log.d("my_debug", "change listener, id_zlecenia: "+id_zlecenia+", id_folder: "+id_folder); + + try { + int id_folder_gui = folderIdsForOrders.get(pos); + int id_zlecenia = jZlecenie.getInt("id_zlecenia"); + + + int id_folder_json = 0; + if( jZlecenie.getString("id_folder").equals("null") ){ + id_folder_json = 0; + } + else { + id_folder_json = jZlecenie.getInt("id_folder"); + } + + // jeśli zlecenie zaznaczone w guiu jest takie samo jak w jsonie to nie ma sensu generować plików ( return ) + if( id_folder_json == id_folder_gui) { + return; + } + + Log.d("my_debug", "change listener, id_zlecenia: "+id_zlecenia+", id_folder: "+id_folder_gui); + + jZlecenie.put("id_folder", id_folder_gui); + + setIdFolderInListaProfil(id_zlecenia, id_folder_gui); + + JSONObject mainJs = new JSONObject(); + JSONObject contentJs = new JSONObject(); + contentJs.put("id_zlecenia", id_zlecenia); + contentJs.put("id_folder", id_folder_gui); + mainJs.put("zlecenie", contentJs); + + Date d = new Date(); + String genName = "folder_"+d.getTime() + ".mod"; + File dstDir = new File(prefs.getString("dir", "") + "/upload_folders_mod"); + if( !dstDir.isDirectory()){ dstDir.mkdirs(); } + + DedalHelper.putFileContent(prefs.getString("dir", "") + "/upload_folders_mod/" + genName, mainJs.toString()); + + /* + // wystartuj/obudź serwis + Context context = getApplicationContext(); + Intent service = new Intent(context, DedalService.class); + context.startService(service); + */ + } catch (JSONException e) { + Log.e(LOG, "", e); + } + + } + } + + + + private void setIdFolderInListaProfil(int id_zlecenia, int id_folder) { + try { + File dLista = new File(prefs.getString("dir", "") + "/baza/lista.profil"); + if( dLista.isFile()){ + String sJson = DedalHelper.getFileContent(dLista.getAbsolutePath()); + JSONObject jFile = new JSONObject(sJson); + + JSONObject jProfiles = jFile.getJSONObject("profile"); + Iterator pKeys = jProfiles.keys(); + //Boolean break_ = false; + + while( pKeys.hasNext()){ + String idProfilu = (String)pKeys.next(); + JSONObject jProfil = jProfiles.getJSONObject(idProfilu); + JSONObject jZlecenia = jProfil.getJSONObject("zlecenia"); + Iterator pKeys2 = jZlecenia.keys(); + while( pKeys2.hasNext() ){ + String id_zlecenia_curr = (String)pKeys2.next(); + if ( id_zlecenia_curr.equals( Integer.toString(id_zlecenia) ) ) { + JSONObject jZlecenie = jZlecenia.getJSONObject(Integer.toString(id_zlecenia)); + if(id_folder == 0) { + jZlecenie.put("id_folder", "null"); + } + else { + jZlecenie.put("id_folder", id_folder); + } + } + else { + continue; + } + } +// if( break_ ) { +// break; +// } + } + DedalHelper.putFileContent(prefs.getString("dir", "") + "/baza/lista.profil", jFile.toString()); + } + + + + } catch (JSONException e) { + Log.e(LOG, "", e); + } + + } + + + @Override + public void onNothingSelected(AdapterView arg0) { + // TODO Auto-generated method stub + + } + + } + + //long lastProfileMod = 0; + //TextView textDataMod; + TextView textGPSMod; + //TextView textUpload; + //ProgressBar progress; + ToggleButton checkZaakceptowane; + boolean isCheckedZaakceptowane = true; + + JSONObject jProfiles; + Spinner sortSpinner = null; + + ArrayList items = new ArrayList(); + ArrayList profileIds = new ArrayList(); + JSONObject jProfil; // obecnie wybrany profil + String id_profilu; //obecnie wybrany id_profilu + LinearLayout listaLayout; + Spinner spinProfil; + Spinner spinFolder; + +// ArrayList sortItems = new ArrayList(); +// ArrayList sortItemsKod = new ArrayList(); + + FilterColumns filterColumns = new FilterColumns(); + + private static final String DEFAULT_SORT_COL = "data_zlecenia"; + +// String sortCol = "data_zlecenia"; +// int bSortASC = -1; +// ArrayList filterItems = new ArrayList(); + + int versionNumber = 0; + String versionName = "Wersja ?"; +// EditText etSearch; + + String search = ""; + + // kkuz: do obsługi katalogów zleceń + int id_folder = -1; // -1 - oznacza brak wybrania folderu (czyli pokaż wszystkie), 0 oznacza pokazanie zleceń nieprzypisnych do folderu + ArrayList folderIds = new ArrayList(); + ArrayList folderNazwy = new ArrayList(); + + ArrayList folderIdsForOrders = new ArrayList(); + ArrayList folderNazwyForOrders = new ArrayList(); + + SparseArray trId_id_zlecenia = new SparseArray(); + + int maxId = 0; + + int curPage = 0; + final int linesPerPage = 50; + int linesCount = -1; // wyswietl liste oblicza. + TextView tIlosc; + + // private boolean isPortret = false; + double latitude; + double longitude; + public static GPSTracker gps; + + RefreshLayoutAndThread rlat = null; + + protected String getDefaultHost(){ + return "";//https://dedal.eos-ksi.pl"; + } + protected String getDefaultFolder(){ + return "/likesoft"; + } + + + @Override + protected void onResume() { + // TODO Auto-generated method stub + super.onResume(); + Log.d("my_debug", "onresume"); + // jeśli użytkownik wrócił z Ustawień i przyznał uprawnienie zarządzania plikami, + // a UI nie został jeszcze zainicjalizowany, to teraz wykonaj inicjalizację + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + if (Environment.isExternalStorageManager()) { + if (spinProfil == null) { + setupUIAndLogic(); + } + } + } + wyswietlListe(); + + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + if (requestCode == REQUEST_APP_PERMISSIONS) { + // Evaluate which permissions were granted and continue initialization. + boolean anyDenied = false; + for (int r : grantResults) { + if (r != PackageManager.PERMISSION_GRANTED) { anyDenied = true; break; } + } + if (anyDenied) { + // Show a short explanation and continue with reduced functionality + Toast.makeText(this, "Część uprawnień nie została przyznana. Aplikacja uruchomi się, ale niektóre funkcje mogą być niedostępne.", Toast.LENGTH_LONG).show(); + } + // kontynuuj inicjalizację bez restartu + setupUIAndLogic(); + return; + } + + // legacy/requested individually - keep fallback + switch (requestCode) { + case REQUEST_READ_PHONE_STATE: + // fallthrough - do a gentle retry of initialization + setupUIAndLogic(); + break; + case REQUEST_ACCESS_FINE_LOCATION: + // nothing special + break; + case REQUEST_POST_NOTIFICATIONS: + // notifications permission handled by service when needed + break; + + default: + break; + } + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + + super.onCreate(savedInstanceState); + // setContentView(R.layout.activity_list); +// if(BuildConfig.DEBUG) +// StrictMode.enableDefaults(); + + //if (DEVELOPER_MODE) + if(BuildConfig.DEBUG){ + StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() + // .detectDiskReads() + // .detectDiskWrites() + .detectNetwork() // or .detectAll() for all detectable problems + .penaltyLog() + .build()); + StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() + .detectLeakedSqlLiteObjects() + // .detectLeakedClosableObjects() + .penaltyLog() + //.penaltyDeath() + .build()); + } + + // centralna prośba o uprawnienia runtime + if (!ensurePermissions()) { + // permissions request started, poczekaj na callback + return; + } + + // jeśli wszystkie wymagane uprawnienia już są przyznane, wykonaj resztę inicjalizacji + setupUIAndLogic(); + + } + + /** + * Sprawdza jakie uprawnienia potrzebne i uruchamia request jeśli coś brakuje. + * Zwraca true gdy wszystkie wymagane uprawnienia są już przyznane. + */ + private boolean ensurePermissions() { + ArrayList toRequest = new ArrayList(); + // telephony: proś o READ_PHONE_STATE dla starych SDK, oraz READ_PHONE_NUMBERS dla nowszych + if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { + toRequest.add(Manifest.permission.READ_PHONE_STATE); + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED) { + toRequest.add(Manifest.permission.READ_PHONE_NUMBERS); + } + } + // location (app używa GPSTracker) - prośba o ACCESS_FINE_LOCATION jeśli nieprzyznane + if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED + && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { + toRequest.add(Manifest.permission.ACCESS_FINE_LOCATION); + } + // notifications (Android 13+) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { + toRequest.add(Manifest.permission.POST_NOTIFICATIONS); + } + } + // WRITE_EXTERNAL_STORAGE only for Android < Q as before + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { + if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { + toRequest.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); + } + } + // Storage permissions - różne podejście dla różnych wersji Androida + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + // Android 11+ - MANAGE_EXTERNAL_STORAGE wymaga specjalnego ekranu Settings + if (!Environment.isExternalStorageManager()) { + // Wyświetl dialog z wyjaśnieniem przed przejściem do ustawień + new AlertDialog.Builder(this) + .setTitle("Wymagane uprawnienie") + .setMessage("Aplikacja potrzebuje dostępu do pamięci urządzenia, aby zapisywać pliki zleceń i zdjęć. " + + "Zostaniesz przekierowany do ustawień, aby przyznać uprawnienie 'Wszystkie pliki'.") + .setPositiveButton("OK", (dialog, which) -> { + try { + Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION); + Uri uri = Uri.fromParts("package", getPackageName(), null); + intent.setData(uri); + startActivityForResult(intent, REQUEST_MANAGE_ALL_FILES); + } catch (Exception e) { + // Fallback dla niektórych urządzeń + Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION); + startActivityForResult(intent, REQUEST_MANAGE_ALL_FILES); + } + }) + .setNegativeButton("Anuluj", (dialog, which) -> { + Toast.makeText(this, "Aplikacja nie będzie działać poprawnie bez dostępu do pamięci", Toast.LENGTH_LONG).show(); + finish(); + }) + .setCancelable(false) + .show(); + return false; + } + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + // Android 10 - WRITE_EXTERNAL_STORAGE + requestLegacyExternalStorage w manifeście + if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { + toRequest.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); + } + } else { + // Android < 10 - standardowe uprawnienia + if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { + toRequest.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); + } + } + + if (toRequest.size() > 0) { + String[] arr = toRequest.toArray(new String[0]); + ActivityCompat.requestPermissions(this, arr, REQUEST_APP_PERMISSIONS); + return false; + } + return true; + } + + /** + * Przeniesiona część inicjalizacji, która ma się wykonać po przyznaniu uprawnień lub jeśli już są przyznane. + */ + private void setupUIAndLogic() { + // ensure default prefs exist (do not tie to permission) + Context context = getApplicationContext(); + prefs = PreferenceManager.getDefaultSharedPreferences(context); + Editor e = prefs.edit(); + if (!prefs.contains("dir")) { + e.putString("dir", Environment.getExternalStorageDirectory()+ "/dedal/init"); + } + e.putBoolean("tablet", true); + e.putInt("refresh", 2); + e.apply(); + + // READ_PHONE_STATE (only if really needed) + int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE); + if (permissionCheck != PackageManager.PERMISSION_GRANTED) { + ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE); + return; + } + +// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { +// if (Settings.System.canWrite(ListActivity.this )) { +// // Do stuff here +// Log.d( "ttt","ttt"); +// } +// else { +// Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS); +// intent.setData(Uri.parse("package:" + this.getPackageName() )); +// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); +// startActivity(intent); +// } +// } + //Log.d("my_debug", "oncreate, id_profilu: "+id_profilu); + //Context context = getApplicationContext(); + //prefs = PreferenceManager.getDefaultSharedPreferences(context); +// if( prefs.getString("dir","").equals("")){ +// // call preferences / login dialog. +// Intent i = new Intent(this, getPreferActivity()); +// startActivityForResult(i, SHOW_PREFERENCES); +// } +// Log.setFileName(prefs.getString("dir", Environment.getExternalStorageDirectory()+ "/likesoftdemo")); + + //this.getExternalFilesDir() + //getExternalFilesDir(null) + Log.setFileName(prefs.getString("dir", Environment.getExternalStorageDirectory()+ getDefaultFolder())); + Log.setEH(); + + //Editor e = prefs.edit(); + File d = new File( prefs.getString("dir", "")); + if( !prefs.getString("dir", "").equals("")){ + if( !d.isDirectory()){ + d.mkdirs(); + } + if( !d.isDirectory()){ + Toast.makeText(context, "nie udalo się utworzyć katalogu do zapisu", Toast.LENGTH_LONG); + } + } + Log.d(LOG, "work directory: " +d.getAbsolutePath()); + if( ! getDefaultHost().equals("")){ + Log.d(LOG, "hostname=" + prefs.getString("hostname", "") + ", ustawiam default: " + getDefaultHost()); + e.putString("hostName", getDefaultHost()); + } + e.commit(); + prefs = PreferenceManager.getDefaultSharedPreferences(context); + + + + gps = new GPSTracker(this); + gps.getLocation(); + + // check if GPS enabled + if(gps.canGetLocation() && gps.isGPSEnabled){ + + latitude = gps.getLatitude(); + longitude = gps.getLongitude(); + //Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); + Log.d(LOG, "Your Location is - \nLat: " + latitude + "\nLong: " + longitude + ", liczba satelitow: " + gps.liczbaSatelitow); + }else{ + // can't get location + // GPS or Network is not enabled + // Ask user to enable GPS/network in settings + gps.showSettingsAlert(); + } + + //Context context = getApplicationContext(); + + PackageInfo pinfo; + try { + pinfo = getPackageManager().getPackageInfo(getPackageName(), 0); + versionNumber = pinfo.versionCode; + versionName = pinfo.versionName; + } catch (NameNotFoundException e2) { + Log.e(LOG, "", e2); + } + + +// Intent service = new Intent(context, DedalService.class); +// context.startService(service); + + + +// RelativeLayout rl = new RelativeLayout(this); + + + LinearLayout rl = new LinearLayout(this); + + rl.setOrientation(LinearLayout.VERTICAL); + //rl.setLayoutParams(LayoutParams.WRAP_CONTENT); + //rl.setMinimumWidth() + //TextView tw = new TextView(this); +// tw.setText("Lista zleceń."); +// tw.setLayoutParams(LayoutParams.WRAP_CONTENT); +// rl.addView(tw); +// tw = new TextView(this); + //tw.setText(" Wersja aplikacji:" + versionName );//+ ", :"+ versionNumber); + setTitle("mDedal - Wersja aplikacji: " + versionName ); + //rl.addView(tw); + + Button headers = new Button(this); + headers.setText("Z"); + headers.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + + Log.d("my_debug", "id_profilu: "+id_profilu); + + Intent intent = new Intent(ListActivity.this, getTableHeadersActivity()); + intent.putExtra("id_profilu", id_profilu); + startActivity(intent); + } + }); + + Button calendar_btn = new Button(this); + calendar_btn.setText("K"); + calendar_btn.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + + //Log.d("my_debug", "id_profilu: "+id_profilu); + + Intent intent = new Intent(ListActivity.this, getCalendarActivity()); + intent.putExtra("id_profilu", id_profilu); + startActivity(intent); + } + }); + + HorizontalScrollView scrollFilter = new HorizontalScrollView(this); + //scrollFilter + rl.addView(scrollFilter); + +// LinearLayout maniLin = new LinearLayout(this); +// maniLin.setOrientation(LinearLayout.VERTICAL); +// scrollFilter.addView(maniLin); + + LinearLayout filterL = new LinearLayout(this); + filterL.setOrientation(LinearLayout.HORIZONTAL); + + //rl.addView( filterL); + scrollFilter.addView( filterL); + + filterL.addView(headers); + filterL.addView(calendar_btn); + + Spinner spin = new Spinner(this); + spinProfil = spin; + filterL.addView(spin); + + Spinner spin_folder = new Spinner(this); + spinFolder = spin_folder; + filterL.addView(spin_folder); + + Button nowy_folder_button = new Button(this); + nowy_folder_button.setText("+"); + nowy_folder_button.setOnClickListener(new EditFolderOnClickListener()); + filterL.addView(nowy_folder_button); + + textGPSMod = new TextView(this); + textGPSMod.setPadding(20, 0, 20, 0); + textGPSMod.setTextAppearance(this, R.style.OpisTextLista); + filterL.addView(textGPSMod); + + //////////////////////////////// + rlat = new RefreshLayoutAndThread(this) { +// @Override +// protected void reloadContent() { +// wyswietlListe(); +// } + @Override + protected void whenThreadNeedToReaoad() { + try { + //Log.d("my_debug", "tera123; "); + int pos = spinProfil.getSelectedItemPosition(); + int pos_folder = spinFolder.getSelectedItemPosition(); + String idProfilu = "EMPTY"; + String idFolder = "Wszystkie"; + if( profileIds.size()>pos && pos >=0){ + idProfilu =profileIds.get(pos); + } + if ( folderIds.size() > pos_folder && pos_folder >= 0 ) { + idFolder = Integer.toString(folderIds.get(pos_folder)); + } + + String sJson = DedalHelper.getFileContent(prefs.getString("dir", "") + "/baza/lista.profil"); + JSONObject jFile = new JSONObject(sJson); + loadFromJson( jFile); + + Log.d("my_debug", "id_profilu w watku: " + id_profilu); + String idProfiluNew = "Nowy"; + if( profileIds.size()>pos && pos >=0){ + idProfiluNew =profileIds.get(pos); + } + if( idProfilu.equals(idProfiluNew)){ + spinProfil.setSelection(pos); + }else{ + spinProfil.setSelection(0); + } + + String idFolderNew = "Nowy"; + if ( folderIds.size() > pos_folder && pos_folder >= 0 ) { + idFolderNew = Integer.toString(folderIds.get(pos_folder)); + } + if( idFolder.equals(idFolderNew)){ + spinFolder.setSelection(pos_folder); + }else{ + spinFolder.setSelection(0); + } + + wyswietlListe(); + +// } catch (FileNotFoundException e) { +// Log.e(LOG, "", e); + } catch (JSONException e) { + Log.e(LOG, "", e); +// } catch (IOException e) { +// Log.e(LOG, "", e); + } + } + @Override + protected void setLastGPSInfo_abstr() { + setLastGPSInfo(); + } + }; //new RefreshLayoutAndThread(getApplicationContext()); + LinearLayout refreshLayout = rlat.getRefreshLayout(); + filterL.addView(refreshLayout); + /////////////////////////// + + Resources res = getResources(); +// if( "1".equals(res.getString(R.string.Portret))){ + + if( true ){ + filterL = new LinearLayout(this); + filterL.setOrientation(LinearLayout.HORIZONTAL); + scrollFilter = new HorizontalScrollView(this); + //scrollFilter + rl.addView(scrollFilter); + scrollFilter.addView( filterL); + } + + SearchView searchView = new SearchView(this); + searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default + searchView.setQueryHint("Wpisz szukane słowo"); + + searchView.setOnQueryTextListener(new OnQueryTextListener() { + + + @Override + public boolean onQueryTextSubmit(String query) { + // TODO Auto-generated method stub + Context context = getApplicationContext(); + Toast.makeText(context, + "szukaj słowa : " + query, + Toast.LENGTH_LONG).show(); + search = query; + wyswietlListe(); + return false; + } + + @Override + public boolean onQueryTextChange(String newText) { + // TODO Auto-generated method stub + search = newText; //nie dzia�a + return false; + } + }); + + filterL.addView(searchView); + checkZaakceptowane = new ToggleButton(this); + checkZaakceptowane.setTextOff("Wszystkie zlecenia"); + checkZaakceptowane.setTextOn("Schowane zakończone"); + checkZaakceptowane.setChecked(isCheckedZaakceptowane); + checkZaakceptowane.setOnCheckedChangeListener(new OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton buttonView, + boolean isChecked) { + isCheckedZaakceptowane = isChecked; + curPage = 0; + wyswietlListe(); + + } + }); + filterL.addView(checkZaakceptowane); + + + // todo: temp commented +// textUpload = new TextView(this); +// textUpload.setPadding(20, 0, 20, 0); +// filterL.addView(textUpload); + TextView textUpload = rlat.getTextUpload(); + filterL.addView(textUpload); + +// filterL = new LinearLayout(this); +// filterL.setOrientation(LinearLayout.HORIZONTAL); +// rl.addView( filterL); + + Button bPrev = new Button(this); + bPrev.setText("<<"); + bPrev.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + + Log.d("my_debug", "page: "+curPage); + if( curPage >0){ + curPage--; + wyswietlListe(); + } + } + }); + filterL.addView(bPrev); +// + tIlosc = new TextView(this); + tIlosc.setText("strona " + (curPage+1) );//+ "/" +(linesCount/linesPerPage+1) ); + filterL.addView(tIlosc); + + Button bNext = new Button(this); + bNext.setText(">>"); + bNext.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + + Log.d("my_debug", "page: "+curPage); + if( curPage < linesCount/linesPerPage){ + curPage++; + wyswietlListe(); + } + } + }); + filterL.addView(bNext); + + Button bClearFilters = new Button(this); + bClearFilters.setText("Czyść filtry"); + bClearFilters.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + filterColumns.reset(); + + Log.d("my_debug", "bClearFilters onclick"); + wyswietlListe(); + } + }); + filterL.addView(bClearFilters); + + Button bShowKP = new Button(this); + bShowKP.setText("KP"); + bShowKP.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(ListActivity.this, getKPActivity()); + intent.putExtra("id_profilu", id_profilu); + startActivity(intent); + } + }); + filterL.addView(bShowKP); + + Button bKPWplaty = new Button(this); + bKPWplaty.setText("Wpłaty KP"); + bKPWplaty.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(ListActivity.this, getKPWplatyActivity()); + intent.putExtra("id_profilu", id_profilu); + startActivity(intent); + } + }); + filterL.addView(bKPWplaty); + + setLastGPSInfo(); + // todo: temp commented, should be: rlat->setLastUpdateInfo(); + rlat.setLastUpdateInfo(); + + + File fLockLogin = new File(prefs.getString("dir", "") + "dedalsrv.wrongLogin"); + if(fLockLogin.exists() || checkIfFirstLogin()){ + Intent i = new Intent(this, getPreferActivity()); + startActivityForResult(i, SHOW_PREFERENCES); + } + //setLastUpdateInfo(); + + + ////////////////// + //Thread t =new Thread(rlat); + rlat.start(); + ////////////////////// + + HorizontalScrollView hs = new HorizontalScrollView(this); + rl.addView(hs); + + ScrollView sw = new ScrollView(this); + hs.addView(sw); + LinearLayout lla = new LinearLayout(this); + //lla.setFocusableInTouchMode(false); + listaLayout = lla; +// ll.setId(1001); + lla.setOrientation(LinearLayout.VERTICAL); +// lla.setPadding(15, 3, 15, 5); + lla.setBackgroundColor(Color.parseColor("#FFA500")); + sw.addView(lla); + + + folderNazwy = new ArrayList(); + folderIds = new ArrayList(); + folderNazwyForOrders = new ArrayList(); + folderIdsForOrders = new ArrayList(); + + folderNazwy.add( "Wszystkie" ); + folderIds.add( -1 ); + folderNazwyForOrders.add( "Nie wybrano" ); + folderIdsForOrders.add( 0 ); + + + // File dLista = new File(prefs.getString("dir", "") + "/baza/lista.profil"); + + + Log.d(LOG, "Wczytywanie listy start."); + try { + String sJson = DedalHelper.getFileContent(prefs.getString("dir", "") + "/baza/lista.profil"); + + if( sJson!= null && sJson.length()>0) { + JSONObject jFile = new JSONObject(sJson); + loadFromJson(jFile); + Log.d("my_debug", "przed set id_porfilu, profileIds.size():" + profileIds.size() + ", id_profilu: " + id_profilu); + if (profileIds != null && profileIds.size() > 0 && id_profilu != null && !"0".equals(id_profilu)) { + Log.d("my_debug", "first if"); + int pos = -1; + for (int i = 1; i < profileIds.size(); i++) { + Log.d("my_debug", "petla. i: " + i + ", profileIds.get(i): " + profileIds.get(i) + ", id_profilu: " + id_profilu); + if (profileIds.get(i) == id_profilu) { + pos = i; + break; + } + } + if (pos > -1) { + spinProfil.setSelection(pos); + } + } + } + +// } catch (FileNotFoundException e1) { +// // TODO Auto-generated catch block +// e1.printStackTrace(); + } catch (JSONException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); +// } catch (IOException e1) { +// // TODO Auto-generated catch block +// e1.printStackTrace(); + } + Log.d(LOG, "Wczytywanie listy JSON zakonczone."); + +// //Profile +// jProfiles = jFile.getJSONObject("profile"); +// Iterator pKeys = jProfiles.keys(); +// while( pKeys.hasNext()){ +// String idProfilu = (String)pKeys.next(); +// JSONObject jProfil = jProfiles.getJSONObject(idProfilu); +// items.add( jProfil.getString("nazwa_profilu")); +// profileIds.add( idProfilu); +// } +// +// ArrayAdapter aa = new ArrayAdapter( +// this, +// android.R.layout.simple_spinner_item, +// items.toArray()); +// +// aa.setDropDownViewResource( +// android.R.layout.simple_spinner_dropdown_item); +// +// spin.setOnItemSelectedListener(new CustomOnItemSelectedListener()); +// spin.setAdapter(aa); +// +// // kkuz: FOLDERY +// JSONObject jFolders = jFile.getJSONObject("foldery"); +// Iterator pKeys2 = jFolders.keys(); +// +// folderNazwy.add( "Nie wybrano" ); +// folderIds.add( 0 ); +// +// while( pKeys2.hasNext()){ +// String idFolder = (String)pKeys2.next(); +// JSONObject jFolder = jFolders.getJSONObject(idFolder); +// //Log.d("my_debug","nazwa1: "+jFolder.getString("nazwa")); +// folderNazwy.add( jFolder.getString("nazwa")); +// folderIds.add( jFolder.getInt("id_folder") ); +// +// folderNazwyForOrders.add( jFolder.getString("nazwa")); +// folderIdsForOrders.add( jFolder.getInt("id_folder") ); +// } +// +// } +// +// } catch (FileNotFoundException e1) { +// Log.e(LOG, "", e1); +// } catch (JSONException fe) { +// Log.e(LOG, "", fe); +// } catch (IOException ie) { +// Log.e(LOG, "", ie); +// } +// +// ArrayAdapter aa_foldery = new ArrayAdapter( +// this, +// android.R.layout.simple_spinner_item, +// folderNazwy.toArray()); +// +// aa_foldery.setDropDownViewResource( +// android.R.layout.simple_spinner_dropdown_item); +// spinFolder.setAdapter(aa_foldery); +// spinFolder.setOnItemSelectedListener(new CustomOnFolderSelectedListener()); + + Log.d("my_debug", "wyswietl_liste w oncreate"); + wyswietlListe(); + + rl.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); + rl.setFocusableInTouchMode(true); + + rl.setOnDragListener(new MyDragListenerBack()); + setContentView(rl); + + } + + private void loadFromJson( JSONObject jFile){ + Log.d("my_debug", "loadFromJson"); + + folderNazwy = new ArrayList(); + folderIds = new ArrayList(); + folderNazwyForOrders = new ArrayList(); + folderIdsForOrders = new ArrayList(); + + folderNazwy.add( "Wszystkie" ); + folderIds.add( -1 ); + folderNazwyForOrders.add( "Nie wybrano" ); + folderIdsForOrders.add( 0 ); + + final String DEFAULT_PROFILE_NAME = "Inspektor-Windykacja"; + + try{ + + // PROFILE + jProfiles = jFile.getJSONObject("profile"); + Iterator pKeys = jProfiles.keys(); + items = new ArrayList(); + profileIds = new ArrayList(); + Integer set_selection_default = null; + for( int i = 0 ; pKeys.hasNext() ; i++ ){ + String idProfilu = (String)pKeys.next(); + JSONObject jProfil_ = jProfiles.getJSONObject(idProfilu); + String nazwa_profilu = jProfil_.getString("nazwa_profilu"); + if( DEFAULT_PROFILE_NAME.equals(nazwa_profilu) ) { + id_profilu = idProfilu; + jProfil = jProfil_; + set_selection_default = i; + } + items.add(nazwa_profilu); + profileIds.add( idProfilu); + } + + ArrayAdapter aa = new ArrayAdapter( + this, + android.R.layout.simple_spinner_item, + items.toArray()); + + aa.setDropDownViewResource( + android.R.layout.simple_spinner_dropdown_item); + + spinProfil.setOnItemSelectedListener(new CustomOnItemSelectedListener()); + spinProfil.setAdapter(aa); + + // DEFAULT + if( set_selection_default != null && set_selection_default >= 0 ) { + spinProfil.setSelection(set_selection_default); + } + + // kkuz: FOLDERY + JSONObject jFolders = null; + //Log.d(LOG, "Lista: " + jFile.toString()); +// if( !jFile.has("foldery") || "null".equals(jFile.getString("foldery")) ) { +// //Log.d("my_debug", "new json"); +// jFolders = new JSONObject(); +// jFile.put("foldery", jFolders); +// } + // dkuz: poprawka jakiś błąd z generacją, przychodzi pusta tabela z serwera. + jFolders = jFile.optJSONObject("foldery"); + if( jFolders == null){ + jFolders = new JSONObject(); + jFile.put("foldery", jFolders); + } + + + //jFolders = jFile.getJSONObject("foldery"); + //JSONArray jFolders = jFile.getJSONArray("foldery"); + Iterator pKeys2 = jFolders.keys(); + + folderNazwy.add( "Nie wybrano" ); + folderIds.add( 0 ); + //if_profilu; + //String i = id_profilu; + //HashMap temp = new HashMap(); + +// HashMap temp = count_orders_per_folder(jFile, id_profilu); +// Log.d("my_debug", "temp: "+temp); + while( pKeys2.hasNext()){ + String idFolder = (String)pKeys2.next(); + JSONObject jFolder = jFolders.getJSONObject(idFolder); + //Log.d("my_debug","nazwa1: "+jFolder.getString("nazwa")); +// Integer count = 0; +// if( !"null".equals(idFolder) && temp.get(Integer.parseInt(idFolder)) != null ) { +// count = temp.get(Integer.parseInt(idFolder)); +// } + folderNazwy.add( jFolder.getString("nazwa") ); //+", "+count ); + folderIds.add( jFolder.getInt("id_folder") ); + + folderNazwyForOrders.add( jFolder.getString("nazwa")); + folderIdsForOrders.add( jFolder.getInt("id_folder") ); + } + +// if( jFolders!= null && jFolders.length()>0){ +// for ( int i=0; i count_orders_per_folder(String id_profilu) { + Log.d("my_debug", "count_orders_per_folder"); + HashMap temp = new HashMap(); + try { + File dLista = new File(prefs.getString("dir", "") + "/baza/lista.profil"); + if( dLista.isFile()){ + String sJson = DedalHelper.getFileContent(prefs.getString("dir", "") + "/baza/lista.profil"); + JSONObject jFile = new JSONObject(sJson);//buf.readLine()); + JSONObject jProfiles = jFile.getJSONObject("profile"); + Iterator pKeys = jProfiles.keys(); + //Boolean break_ = false; + int count_all = 0; + while( pKeys.hasNext()){ + String idProfilu = (String)pKeys.next(); + //Log.d("my_debug", "idProfil: "+idProfilu+", id_profilu: "+id_profilu); + if( idProfilu.equals(id_profilu) ) { + JSONObject jProfil = jProfiles.getJSONObject(idProfilu); + JSONObject jZlecenia = jProfil.getJSONObject("zlecenia"); + Iterator pKeys2 = jZlecenia.keys(); + while( pKeys2.hasNext() ){ + String id_zlecenia_curr = (String)pKeys2.next(); + JSONObject jZlecenie = jZlecenia.getJSONObject(id_zlecenia_curr); + //Log.d("my_debug", "id_folder_curr: "+jZlecenie.getString("id_folder")); + int id_folder_curr = 0; + if( !"null".equals(jZlecenie.getString("id_folder")) ) { + id_folder_curr = jZlecenie.getInt("id_folder"); + } + int count = 0; + if( temp.get(id_folder_curr) != null ) { + count = temp.get(id_folder_curr); + } + count++; + //Log.d("my_debug", id_folder_curr+ ", put count:"+count); + temp.put(id_folder_curr, count ); + + count_all++; + temp.put(-1, count_all ); + } + } +// if( break_ ) { +// break; +// } + } +// } + + + } + } catch (JSONException e) { + Log.e(LOG, "", e); +// } catch (FileNotFoundException e) { +// // TODO Auto-generated catch block +// Log.e(LOG, "", e); +// } catch (IOException e) { +// // TODO Auto-generated catch block +// Log.e(LOG, "", e); + } + return temp; + } + + //String sLastInfo = ""; +/////// + +///////// + private void setLastGPSInfo(){ + //gps.isGPSEnabled + //gps.getLocation(); + latitude = gps.getLatitude(); + longitude = gps.getLongitude(); + + textGPSMod.post(new Runnable() { + @Override + public void run() { + if( !gps.isGPSEnabled){ + textGPSMod.setText("GPS!" ); + textGPSMod.setTextColor(Color.RED); + }else{ + textGPSMod.setText("GPS\n("+gps.liczbaSatelitow+")"); //+gps.isGPSEnabled +// + " pozycja \nx:"+latitude + ", y:"+longitude); + textGPSMod.setTextColor(Color.BLACK); + } + } + }); + + + } +// private int licznikUpdates=0; +// //private static String kreciolek[] = new String[]{"|", "/", "-", "\\"}; +// private String sAktualizacja = ""; +/////////// + +//////////// +//TableLayout + private void wyswietlListe(){ + + if( listaLayout!= null) { + listaLayout.removeAllViews(); + TextView tw = new TextView(this); + if( id_profilu != null) { + tw.setText("Trwa wczytywanie listy zleceń.. " );//+ id_profilu); + }else{ + //zaloguj się. + tw.setText("Zaloguj się." ); +// Intent i = new Intent(ListActivity.this, getPreferActivity()); +// startActivityForResult(i, SHOW_PREFERENCES); + } + Log.d("my_debug", "id_profilu w wyswietlListe: "+id_profilu); + tw.setTextSize(26); + listaLayout.addView(tw); + if( jProfil != null){ + + listaLayout.post(new Runnable() { + + @Override + public void run() { + JSONArray jKolumny; + try { + jKolumny = jProfil.getJSONArray("profil_kolumny"); + JSONObject jZlecenia= new JSONObject(jProfil.getString("zlecenia")); + listaLayout.removeAllViews(); + wyswietlListe( listaLayout, jZlecenia, jKolumny); + } catch (JSONException e) { + //Log.e(LOG, "", e); + listaLayout.removeAllViews(); + TextView tw = new TextView(ListActivity.this); + tw.setText("Brak zleceń"); + tw.setTextSize(26); + listaLayout.addView(tw); + + } + + } + }); + } + } + + } + private void wyswietlListe(LinearLayout lla, JSONObject jZlecenia, JSONArray jKolumny) + throws JSONException { + // obsługa nulla + if (jZlecenia == null) { + lla.removeAllViews(); + TextView tw; + tw = new TextView(this); + tw.setText("Błąd pobierania danych. Sprawdź połączenie z internetem."); + lla.addView(tw); + + } else {// obsługa nulla + //////// ilość zleceń w folderze + HashMap temp = count_orders_per_folder(id_profilu); + Log.d("my_debug", "temp: " + temp); + ArrayList folderNazwy_loc = new ArrayList(); + for (int k = 0; k < folderIds.size(); k++) { + int id_folderu = folderIds.get(k); + String count = ", 0"; + //Log.d("my_debug", "id_folderu: "+id_folderu); + if (temp.get(id_folderu) != null) { + count = ", " + temp.get(id_folderu); + } + + folderNazwy_loc.add(folderNazwy.get(k) + count); + } + ArrayAdapter aa_1 = new ArrayAdapter( + this, + android.R.layout.simple_spinner_item, + folderNazwy_loc.toArray()); + + aa_1.setDropDownViewResource( + android.R.layout.simple_spinner_dropdown_item); + //spinFolder.setOnItemSelectedListener(null); + if (id_folder == -1) { + spinFolder.setAdapter(aa_1); + } + spinFolder.setOnItemSelectedListener(new CustomOnFolderSelectedListener()); + ///////// + + Iterator keys = jZlecenia.keys(); + + + TableLayout tl = new TableLayout(this); + tl.setPadding(0, 15, 0, 0); + //tl.setGravity(Gravity.TOP); + lla.addView(tl); + names = new ArrayList(); + TableRow tr = new TableRow(this); + // tr.setPadding(5, 10, 5, 10); + + // tr.setBackgroundColor(Color.parseColor("#FAFAD2"));// #FAFAD2 + TextView tw; + tw = new TextView(this); + tw.setText("Data \nzapisu"); + tw.setPadding(5, 3, 5, 2); + tr.addView(tw); + + for (int k = 0; k < jKolumny.length(); k++) { + MTextView mtw = new MTextView(this); + mtw.setTextAppearance(this, R.style.OpisText); + String kod = jKolumny.getJSONObject(k).getString("kod"); + mtw.setCode(kod); + String nazwa = jKolumny.getJSONObject(k).getString("nazwa"); + + int j = filterColumns.getIndexOfCode(kod); + if (j >= 0) { + mtw.setTextColor(Color.RED); + int bSortASC = filterColumns.getBSortASC(j); + int lp = j + 1; + nazwa = nazwa + " | " + lp + "."; + if (bSortASC > 0) { + nazwa = nazwa + " [/\\]"; + + } else if (bSortASC < 0) { + nazwa = nazwa + " [\\/]"; + } + } + /* + if( kod.equals(sortCol)){ + mtw.setTextColor(Color.RED); + if( bSortASC>0){ + nazwa = nazwa + " [/\\]"; + + }else{ + nazwa = nazwa + " [\\/]"; + } + } + */ + + // + mtw.setText(nazwa); + //tw.setBackgroundColor(Color.parseColor("#AFA5F0"));// #FAFAD2 + mtw.setPadding(5, 3, 5, 2); + // tw.setTextSize(TypedValue.COMPLEX_UNIT_MM, 5); + mtw.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + if (v instanceof MTextView) { + MTextView mtw = (MTextView) v; + + // wyswietl dialog filtrowania/sortowania + + wyswietlFiltrKolumny(mtw.getCode()); + + // bSortASC *=-1; + // sortCol = mtw.getCode(); + + // wyswietlListe(); + } + + } + + }); + tr.addView(mtw); + + } + + MTextView mtw_folder = new MTextView(this); + mtw_folder.setTextAppearance(this, R.style.OpisText); + mtw_folder.setText("Grupa"); + //tw.setBackgroundColor(Color.parseColor("#AFA5F0"));// #FAFAD2 + mtw_folder.setPadding(5, 3, 5, 2); + tr.addView(mtw_folder); + + tl.addView(tr); + + ArrayList aM = new ArrayList(); + + //Log.d("ListActivity", "Kolumna sortowania: "+ sortCol + ", bSortASC:"+ bSortASC); + + + while (keys.hasNext()) { + + String id = (String) keys.next(); + JSONObject jZlecenie = jZlecenia.getJSONObject(id); + if ((id_folder > 0 && jZlecenie.has("id_folder") && !jZlecenie.getString("id_folder").equals("null") && jZlecenie.getInt("id_folder") == id_folder) || + (id_folder == 0 && jZlecenie.getString("id_folder").equals("null")) || + id_folder == -1) { + if (isCheckedZaakceptowane) { + //JSONObject p = jZlecenie.getJSONObject("param"); + String status = jZlecenie.getString("status"); + if (!"wykonane_zaak".equals(status)) { + aM.add(jZlecenie); + } + } else + aM.add(jZlecenie); + } + } + + boolean do_normal = true; + //Log.d("my_debug", "łojojojoj"); + if (id_folder > 0) { + File dtemp = new File(prefs.getString("dir", "") + "/temp/kolejnosc_foldery_" + id_folder + ".json"); + JSONArray jkolejnosc_zlecen; + if (dtemp.exists()) { + String sJson = DedalHelper.getFileContent(dtemp.getAbsolutePath()); + JSONObject jFile = new JSONObject(sJson); + if (jFile.has("kolejnosc")) { + jkolejnosc_zlecen = jFile.getJSONArray("kolejnosc"); + if (jkolejnosc_zlecen != null) { + //Log.d("my_debug", "jkolejnosc_zlecen: "+jkolejnosc_zlecen.toString()); + Collections.sort(aM, new MyComparator_sortInFolder(jkolejnosc_zlecen)); + do_normal = false; + } + } + //Log.d("my_debug", "1: "+jKolumny.toString()); + } else { + //if(aM) + //Log.d("my_debug", "nie ma pliku"); + Collections.sort(aM, new Comparator() { + @Override + public int compare(JSONObject lhs, JSONObject rhs) { + // TODO Auto-generated method stub + try { + //Log.d("my_debug", "sortuje po serwerze"); + if (lhs.has("kolejnosc_w_folderze") && !lhs.getString("kolejnosc_w_folderze").equals("null") && + rhs.has("kolejnosc_w_folderze") && !rhs.getString("kolejnosc_w_folderze").equals("null")) { + //Log.d("my_debug", "kol w fol: "+lhs.getInt("kolejnosc_w_folderze")+"|"+rhs.getInt("kolejnosc_w_folderze")); + if (lhs.getInt("kolejnosc_w_folderze") < rhs.getInt("kolejnosc_w_folderze")) { + return -1; + } else { + return 1; + } + } else { + return 0; + } + } catch (JSONException e) { + Log.e(LOG, "", e); + } + return 0; + } + }); + do_normal = false; + } + } + if (do_normal) { + Log.d("my_debug", "do normal"); + Collections.sort(aM, new Comparator() { + @Override + public int compare(JSONObject lhs, JSONObject rhs) { + // TODO Auto-generated method stub + try { + boolean do_default = false; + if (filterColumns.getSize() > 0) { + int comp_val = 0; + for (int i = 0; i < filterColumns.getSize(); i++) { + String sortCol = filterColumns.getSortCol(i); + int bSortASC = filterColumns.getBSortASC(i); + comp_val = lhs.getString(sortCol).compareTo(rhs.getString(sortCol)) * bSortASC; + if (comp_val == 0) { + continue; + } else { + return comp_val; + } + } + return comp_val; + + } else { + do_default = true; + } + + if (do_default) { + if (lhs.has(DEFAULT_SORT_COL) && rhs.has(DEFAULT_SORT_COL)) { + return lhs.getString(DEFAULT_SORT_COL).compareTo(rhs.getString(DEFAULT_SORT_COL)) * (-1); + } + return 0; + } + + } catch (JSONException e) { + } + return 0; + } + }); + } + + // wyswietl_tabele_zlecen(jKolumny, tl, aM); + Thread wt = new Thread(new MyTabelaThread(jKolumny, tl, aM)); + wt.start(); + + if (id_folder > 0) { + Button b = new Button(ListActivity.this); + b.setText("Zapisz kolejność na serwerze"); + b.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + Date d = new Date(); + String genName = "kolejnosc_foldery_" + d.getTime() + ".mod"; + File dstDir = new File(prefs.getString("dir", "") + "/upload_kolejnosc_foldery_mod"); + if (!dstDir.isDirectory()) { + dstDir.mkdirs(); + } + File dtemp = new File(prefs.getString("dir", "") + "/temp/kolejnosc_foldery_" + id_folder + ".json"); + if (dtemp.exists()) { + JSONObject jFile; + try { + String sJson = DedalHelper.getFileContent(dtemp.getAbsolutePath()); + jFile = new JSONObject(sJson); + jFile.put("id_folder", id_folder); + + DedalHelper.putFileContent(prefs.getString("dir", "") + "/upload_kolejnosc_foldery_mod/" + genName, jFile.toString()); + + } catch (JSONException e) { + Log.e(LOG, "", e); + } + } + // wystartuj/obudz serwis + Context context = getApplicationContext(); + Intent service = new Intent(context, DedalService.class); + context.startService(service); + } + }); + LinearLayout llb = new LinearLayout(this); + llb.setOrientation(LinearLayout.HORIZONTAL); + llb.addView(b); + listaLayout.addView(llb); + + } + spinProfil.setFocusable(true); + spinProfil.requestFocus(); + + } // obsługa nulla + } + private void wyswietl_tabele_zlecen(JSONArray jKolumny, TableLayout tl, + ArrayList aM) throws JSONException { + TextView tw; + int i = 0; + trId_id_zlecenia.clear(); +// int limit = 0; + int poczatkowy = linesPerPage * curPage; + int koncowy = linesPerPage * (curPage+1); + + for( int z=0; z= koncowy ){ + i++; + continue; + } + + +// wyswietl_wierszTR(tl, jKolumny, jZlecenie, i); + tl.post(new MyWiersTRThread(tl, jKolumny, jZlecenie, i%linesPerPage)); + + if( i%10 == 0){ + try { + Thread.sleep(50); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + i++; + } + linesCount = i; + //wyswietl_linie_konca(tl); + tl.post(new Wyswietl_linie_konca_Thread(tl)); + } + private void wyswietl_linie_konca(TableLayout tl) { + TextView tw; + TableRow tr = new TableRow(this); + tr.setPadding(5, 1, 5, 0); + tw = new TextView(this); + tw.setText(" "); + tr.addView(tw); + + tl.addView( tr); + + + tIlosc.setText("strona " + (curPage+1) + " / " +(linesCount/linesPerPage+1)); + } + private void wyswietl_wierszTR(TableLayout tl, JSONArray jKolumny, + JSONObject jZlecenie, int i) throws JSONException { + + String id = jZlecenie.getString("id_zlecenia"); + Integer id_int = jZlecenie.getInt("id_zlecenia"); + + TableRow tr = utworz_wiersz(i, id, id_int); + + TextView tw; + tw = wyswietl_status_zlecenia(id); + tw.setBackgroundColor(Color.LTGRAY); + //sprawdzic, czy uploady nowe są z tego zlecenia + sprawdzUploadyZlecenia(tw, id); + tr.addView(tw); + + wyswietlLinie(jKolumny, tr, jZlecenie); +// tr.post(new MyWyswietlLinieThread(jKolumny, tr, jZlecenie)); + + tr.setPadding(5, 1, 5, 0); + tl.addView(tr); + } + + private TableRow utworz_wiersz(int i, String id, Integer id_int) { + TableRow tr; + tr = new TableRow(this); + tr.setId(i); + trId_id_zlecenia.put(i, id_int); + maxId = i; + tr.setGravity(Gravity.CENTER_VERTICAL); +// tr.setBackgroundColor(Color.parseColor("#FAFAD2"));// #FAFAD2 + ustawClickListener(tr); + + if( names == null ) { + names = new ArrayList(); + } + + names.add(id + ".json"); + return tr; + } + private TextView wyswietl_status_zlecenia(String id) { + + File file = new File(prefs.getString("dir", "") + "/baza/" + id + ".json"); + Date date = new Date(file.lastModified()); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd \nHH:mm:ss"); + File fileMod = new File(prefs.getString("dir", "") + "/baza/" + id + ".mod"); + + TextView tw; + tw = new TextView(this); + tw.setText(sdf.format(date)); + tw.setTextAppearance(this, R.style.OpisTextLista); + + if( fileMod.isFile()){ + tw.setText("Jeszcze nie \nwysłane na serwer!"); + } + return tw; + } + private void wyswietl_foldery(TableRow tr, JSONObject jZlecenie + ) throws JSONException { + + ArrayAdapter aa_foldery = new ArrayAdapter( + this, + android.R.layout.simple_spinner_item, + folderNazwyForOrders.toArray()); + + aa_foldery.setDropDownViewResource( + android.R.layout.simple_spinner_dropdown_item); + + Spinner spin_folder = new Spinner(this); + + int selected_pos = 0; + + spin_folder.setAdapter(aa_foldery); + + //Log.d("my_debug", "tro1"); + for(int pos = 0 ; pos < folderIdsForOrders.size() ; pos++ ) { + //Log.d("my_debug", "id_zlecenia: "+jZlecenie.getString("id_zlecenia")+", pos: "+pos+", folderIds.get(pos): " +folderIds.get(pos)+", jZlecenie.getInt(id_folder): "+jZlecenie.getInt("id_folder")); + if( jZlecenie.getString("id_folder").equals("null") ){ + selected_pos = 0; + } + else if( folderIdsForOrders.get(pos) == jZlecenie.getInt("id_folder") ) { + selected_pos = pos; + break; + } + } + //Log.d("my_debug", "tro2"); + spin_folder.setSelection(selected_pos); + spin_folder.setOnItemSelectedListener(new ChangeZlecenieFolderSelectedListener(jZlecenie)); + + spin_folder.setBackgroundColor(Color.WHITE); + + tr.addView(spin_folder); + + if( id_folder > 0 ) { + + tr.setOnDragListener(new MyDragListener(Color.CYAN, Color.GREEN)); + TextView tw_move = new TextView(this); + tw_move.setText("przesuń"); + tr.addView(tw_move); + tw_move.setOnTouchListener(new MyTouchListener(tr)); + } + + } + + public void showDatePickerDialog(TextView tv, Integer nr_zlecenia, String data_walidacja_do) { + //DialogFragment newFragment = new DatePickerFragment(); + DatePickerFragment newFragment = new DatePickerFragment(); + newFragment.nr_zlecenia = nr_zlecenia; + newFragment.act = this; + newFragment.data_walidacja_do = data_walidacja_do; + newFragment.tv = tv; + //newFragment.show(((FragmentActivity) getActivity()).getSupportFragmentManager(), "datePicker"); + newFragment.show(getFragmentManager(), "datePicker"); + + } + + private static final String DATA_KOD = "nast_wizyta_data"; + private static final String DATA_TYP_KOD = "nast_wizyta_typ"; + + private void wyswietlLinie(JSONArray jKolumny, TableRow tr, + final JSONObject jZlecenie) throws JSONException { + for( int k=0; k< jKolumny.length(); k++) + { + TextView tw = new TextView(this); + tw.setTextAppearance(this, R.style.OpisText); + tw.setBackgroundColor(Color.WHITE);// #FAFAD2 + tw.setPadding(5, 10, 5, 5); + + String kod =jKolumny.getJSONObject(k).getString("kod"); + + if( kod.equals(DATA_KOD)) { + + // sprawdz, czy pierwsza wizyta + //if( pierwsza_wizyta(jKolumny)) + String typ = jZlecenie.getString(DATA_TYP_KOD); + //Log.d("my_debug", "Data wizyty: " +jZlecenie.getString(DATA_KOD)+ ", typ:" + typ); + if( typ==null || typ.equals("") || typ.equals("null") || typ.equals("pierwsza_wizyta") || typ.equals("nastepna_wizyta") ) { + //nast_wizyta_typ + //Log.d("my_debug", "Możliwa edycja daty"); + Integer rowId = tr.getId(); + final Integer nr_zlecenia = trId_id_zlecenia.get(rowId); + tw.setBackgroundColor(Color.YELLOW); + tw.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View view) { + String data_obslugi = null; + try { + data_obslugi = jZlecenie.getString("data_obslugi"); + } catch (JSONException e) { + e.printStackTrace(); + } + TextView tv = (TextView)view; + showDatePickerDialog(tv, nr_zlecenia, data_obslugi); + + Log.d("my_debug", "Wybrano edycje daty wizyty nr: " + nr_zlecenia + " po zmianie "); + // wyswietlListe(); + } + }); + } +// else{ +// Toast.makeText(this, "Nie można zmieniać daty tego zlecenia", +// Toast.LENGTH_LONG).show(); +// } + } + + tw.setText(DedalHelper.getValueFromKod(kod, jZlecenie)); + + + tr.addView(tw); + + } + //foldery + wyswietl_foldery(tr, jZlecenie ); + } + + private void sprawdzUploadyZlecenia(TextView tw, String id) { + File dir = new File(prefs.getString("dir", "")); + File dirUpload = new File(dir + "/upload"); + File dirZlecenie = new File(dirUpload + "/"+ id); + if( dirZlecenie.isDirectory()){ + File f[] = dirZlecenie.listFiles(new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.toLowerCase().endsWith(".mod"); + } + }); + if( f.length>0){ + //tw.setText("Jest inna \nmodyfikacja w upload!"); + tw.setText("Wysyłka na \nserwer"); + Log.d("ListActivity", "Jest inna modyfikacja w upload"); + } + } + } + private String getCurDate(){ + Date d = new Date(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd"); + return sdf.format(d); + } + + boolean checkIfFirstLogin(){ + //sprawdz, czy pierwsze zalogowanie bylo + boolean firstLogin = false; + File fFirstLogin = new File(prefs.getString("dir", "") + "/dedalsrv.firstLogin"); + if( fFirstLogin.isFile()) { + BufferedReader buf = null; + try { + String sFile = ""; + if (fFirstLogin.exists()) { + buf = new BufferedReader(new FileReader(fFirstLogin)); + sFile = buf.readLine().toLowerCase(); + buf.close(); + } + String curDate = getCurDate(); + if (!sFile.contains(curDate)) { + //return true; + firstLogin = true; + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + //zapisz bieżącą datę do pliku + PrintWriter pw; + try { + pw = new PrintWriter( + new FileWriter(fFirstLogin, false)); + pw.write(getCurDate()); + pw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + return firstLogin; + } + private void ustawClickListener(TableRow tr) { + tr.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + // TODO Auto-generated method stub + v.setBackgroundColor(Color.RED); + if( v instanceof ViewGroup){ + ViewGroup vg = (ViewGroup)v; + int cc = vg.getChildCount(); + for( int i=0; i0){ + String id_zlecenia = ""+id + ".json"; + +// if( id_zlecenia.equals(names.get(cur_id))){ +// // można biezace edytować +// ret = false; +// break; +// } + + +// AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); +// alertDialog.setTitle( "Uwaga");//res.getString(R.string.zakanczanie_wizyty) ); +// alertDialog.setMessage("Posiadasz nieprzerobione stare wizyty.
" + +// " Zaplanuj sprawy na kolejne dni." + +// " Sprawa nr. " + id_zlecenia + " z dnia: "+nast_wizyta_data ); +// alertDialog.setPositiveButton("Anuluj", new DialogInterface.OnClickListener() { +// public void onClick(DialogInterface dialog,int which) { +// //mod_json_files(false); +// dialog.dismiss(); +// } +// }); +// alertDialog.show(); + + if( nr_sprawy!= null){ + message += "nr. sprawy: " + id + " z dnia: " + nast_wizyta_data + "\n"; + }else { + message += "zlecenie nr. " + id + " z dnia: " + nast_wizyta_data + "\n"; + } + + //return; + // ret = true; + //break; + ilosc_nieprzerobionych++; + if( ilosc_nieprzerobionych>=10){ + break; + } + } + } + } + } + if( ilosc_nieprzerobionych>0){ + AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); + alertDialog.setTitle( "Uwaga");//res.getString(R.string.zakanczanie_wizyty) ); +// alertDialog.setMessage("Posiadasz nieprzerobione stare wizyty. Zaplanuj sprawy na kolejne dni"); + alertDialog.setMessage( "Posiadasz nieprzerobione stare wizyty.\n" + + " Zaplanuj sprawy na kolejne dni.\n" + + "wyświetlone pierwsze " + ilosc_nieprzerobionych + " wizyt:\n"+ + message); + alertDialog.setPositiveButton("Anuluj", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int which) { + //mod_json_files(false); + dialog.dismiss(); + + Intent intent = new Intent(ListActivity.this, + getMainActivity()); + File f = new File(prefs.getString("dir", "") + + "/baza/" + names.get(cur_id)); + Uri u = Uri.fromFile(f); + intent.setData(u); + intent.putExtra("filename", names.get(cur_id)); + startActivity(intent); + + + } + }); + alertDialog.show(); + ret = true; // blokuj wejście, czekaj na zamknięcie dialogu. + } + + } catch (JSONException e) { + e.printStackTrace(); + } + return ret; + } + + + private final class MyTouchListener implements OnTouchListener { + + TableRow tr; + + public MyTouchListener (TableRow tr) { + this.tr = tr; + } + + @Override + public boolean onTouch(View view, MotionEvent motionEvent) { + if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { + ClipData data = ClipData.newPlainText("", ""); + //DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view); + //view.startDrag(data, shadowBuilder, view, 0); + //view.setVisibility(View.INVISIBLE); + //DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(tr); + MyDragShadowBuilder myShadowBuilder = new MyDragShadowBuilder(tr); + + Point point = new Point(); + point.set(10, 0); + Point point2 = new Point(); + point2.set(300, 20); + //shadowBuilder.onProvideShadowMetrics(point2, point); + //tr.startDrag(data, shadowBuilder, view, 0); + tr.startDrag(data, myShadowBuilder, view, 0); + tr.setVisibility(View.INVISIBLE); + return true; + } else { + return false; + } + } + } + + private static class MyDragShadowBuilder extends View.DragShadowBuilder { + + public MyDragShadowBuilder(View v) { + super(v); + } + + @Override + public void onProvideShadowMetrics (Point size, Point touch){ + int width = getView().getWidth(); + int height = getView().getHeight(); + + size.set(width, height); + touch.set(width-20,10); + } + } + + class MyDragListenerBack implements OnDragListener { + + @Override + public boolean onDrag(View onDropEl, DragEvent event) { + int action = event.getAction(); + View movingEl = (View) event.getLocalState(); + movingEl = ((View)movingEl.getParent()); + switch (event.getAction()) { + case DragEvent.ACTION_DRAG_STARTED: + // do nothing + break; + case DragEvent.ACTION_DRAG_ENTERED: + //v.setBackgroundDrawable(enterShape); + //onDropEl.setBackgroundColor(Color.GRAY); + break; + case DragEvent.ACTION_DRAG_EXITED: + //v.setBackgroundDrawable(normalShape); + //onDropEl.setBackgroundColor(Color.RED); + break; + case DragEvent.ACTION_DROP: + // Dropped, reassign View to ViewGroup + movingEl.setVisibility(View.VISIBLE); + break; + case DragEvent.ACTION_DRAG_ENDED: + //v.setBackgroundDrawable(normalShape); + default: + break; + } + return true; + } + + } + + class MyDragListener implements OnDragListener { + + int color_entered = 0; + int color_exited = 0; + + public MyDragListener(int color_entered, int color_exited) { + this.color_entered = color_entered; + this.color_exited = color_exited; + } + + @Override + public boolean onDrag(View onDropEl, DragEvent event) { + int action = event.getAction(); + View movingEl = (View) event.getLocalState(); + + int side = Math.round(event.getY() - onDropEl.getMeasuredHeight() / 2 ); // side < 0 uposzczone po lewej stronie elementu, side > 0 upuszczone po prawej stronie + switch (event.getAction()) { + case DragEvent.ACTION_DRAG_STARTED: + // do nothing + break; + case DragEvent.ACTION_DRAG_ENTERED: + //v.setBackgroundDrawable(enterShape); + onDropEl.setBackgroundColor(color_entered); + break; + case DragEvent.ACTION_DRAG_EXITED: + //v.setBackgroundDrawable(normalShape); + //onDropEl.setBackgroundColor(color_exited); + onDropEl.setBackgroundColor(0x00000000); + break; + case DragEvent.ACTION_DROP: + // Dropped, reassign View to ViewGroup + + int id_moving = ((View)movingEl.getParent()).getId(); + int id_drop = onDropEl.getId(); + + JSONObject jmain = new JSONObject(); + JSONArray jfolder = new JSONArray(); + // create Json + +// float x = event.getX(); +// float y = event.getY(); + + + Log.d("my_debug", "side: "+side); + + + //try { + for (int i = 0 ; i < 200 ; i++ ) { + + //int tr_id = trIds.get(i); + TableRow v = (TableRow)ListActivity.this.findViewById(i); + if ( v == null) { + break; + } + if( i == id_drop || i == id_moving) { + //if( id_drop < id_moving ) { + if( i == id_drop ) { + //i = id_moving; + TableRow v_temp = null; + //JSONObject jcurr = null; + if(side >= 0 ) { + + v_temp = (TableRow)ListActivity.this.findViewById(id_drop); + jfolder.put(trId_id_zlecenia.get(id_drop)); + + v_temp = (TableRow)ListActivity.this.findViewById(id_moving); + if( v_temp != null ) { + jfolder.put(trId_id_zlecenia.get(id_moving)); + } + } + else { + v_temp = (TableRow)ListActivity.this.findViewById(id_moving); + if( v_temp != null ) { + jfolder.put(trId_id_zlecenia.get(id_moving)); + } + + v_temp = (TableRow)ListActivity.this.findViewById(id_drop); + jfolder.put(trId_id_zlecenia.get(id_drop)); + //jprofil.put(jcurr); + } + } + if( i == id_moving ) { + continue; + } + } + else { + JSONObject jcurr = new JSONObject(); + + jfolder.put(trId_id_zlecenia.get(i)); + } + } + + + + try { + jmain.put("kolejnosc", jfolder); + } catch (JSONException e1) { + Log.e(LOG, "", e1); + } + + Log.d("my_debug", jmain.toString()); + + onDropEl.setBackgroundColor(Color.DKGRAY); + movingEl.setVisibility(View.VISIBLE); + + String genName = "kolejnosc_foldery_"+id_folder+".json"; + File dstDir = new File(prefs.getString("dir", "") + "/temp"); + if( !dstDir.isDirectory()){ dstDir.mkdirs(); } + File fMod = new File(prefs.getString("dir", "") + "/temp/" + genName); + FileOutputStream fos; + try { + fos = new FileOutputStream(fMod); + fos.write(jmain.toString().getBytes()); + fos.flush(); + fos.close(); + } catch (FileNotFoundException e) { + Log.e(LOG, "", e); + } catch (IOException e) { + Log.e(LOG, "", e); + } + //TableHeadersActivity.this.recreate(); + //drawContent(); + wyswietlListe(); + + break; + case DragEvent.ACTION_DRAG_ENDED: + //v.setBackgroundDrawable(normalShape); + default: + break; + } + return true; + } + + } + + + private void wyswietlFiltrKolumny(final String code) { + // TODO Auto-generated method stub + + // checkboxy wartosci + Set wartosci = wczytajWartosciKolumny( code ); + final ArrayList listaCheckbox = new ArrayList(); + + AlertDialog.Builder alertDialog = new AlertDialog.Builder(ListActivity.this); + alertDialog.setTitle( "Filtrowanie/Sortowanie po kolumnie" ); + // alertDialog.setMessage( "Wybierz opcję:" ); + final LinearLayout lDialog = new LinearLayout(ListActivity.this); + lDialog.setOrientation(LinearLayout.VERTICAL); + + final LinearLayout ll = new LinearLayout(ListActivity.this); + ll.setOrientation(LinearLayout.VERTICAL); + + // sortowanie ASC, DESC + RadioGroup rg = new RadioGroup(this); + rg.setOrientation(LinearLayout.HORIZONTAL); + lDialog.addView(rg); + CheckBox cb; + final RadioButton rbBezSortowania = new RadioButton(this); + rbBezSortowania.setText("Bez sortowania"); // todo + rg.addView(rbBezSortowania); + rbBezSortowania.setChecked(true); + final RadioButton rbRosnaco = new RadioButton(this); + rbRosnaco.setText("Rosnąco"); // todo + rg.addView(rbRosnaco); + final RadioButton rbMalejaco = new RadioButton(ListActivity.this); + rbMalejaco.setText("Malejąco"); // todo + rg.addView(rbMalejaco); + + int j = -1; + if( filterColumns.getSize() > 0 ) { + j = filterColumns.getIndexOfCode(code); + if( j >= 0 ) { + //Log.d("my_debug", "sortColArr: "+sortColArr+", code: "+code+", j: "+j+"bSortASCArr.get(j): "+bSortASCArr.get(j)); + if( filterColumns.getBSortASC(j) > 0 ) { + rbRosnaco.setChecked(true); + } else if( filterColumns.getBSortASC(j) < 0 ) { + rbMalejaco.setChecked(true); + } + else { + rbBezSortowania.setChecked(true); + } + } + } + + /* + if( sortCol.equals(code) ){ + if( bSortASC<0){ + + rbRosnaco.setChecked(true); + }else{ + rbMalejaco.setChecked(true); + } + } + */ + + final Button bZaznaczAll = new Button(this); + bZaznaczAll.setText("Wszystko"); + rg.addView(bZaznaczAll); + bZaznaczAll.setOnClickListener(new OnClickListener() { + boolean selected = true; + @Override + public void onClick(View view) { + for (int i = 0; i < listaCheckbox.size(); i++) { + CheckBox cb = listaCheckbox.get(i); + String search = cb.getText().toString(); + cb.setChecked(selected); + } + if( selected){ + bZaznaczAll.setText("Odznacz"); + }else{ + bZaznaczAll.setText("Wszystko"); + } + selected = !selected; + } + }); + + + + // filter input field + EditText tw = new EditText(this); + lDialog.addView(tw); + tw.addTextChangedListener(new TextWatcher() { + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + } + + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + @Override + public void afterTextChanged(Editable s) { + //setModified(); + String match = s.toString(); + Log.d("my_debug", "after TEXT CHANGED: " + s.toString()); + // + ll.removeAllViews(); + for (int i = 0; i < listaCheckbox.size(); i++) { + CheckBox cb = listaCheckbox.get(i); + String searchTo = cb.getText().toString(); + if( match.length()==0 || searchTo.toLowerCase().contains(match.toLowerCase())) { + ll.addView(cb); + } + + } + +// if( match.length()>0) { +// for (int i = 0; i < listaCheckbox.size(); i++) { +// CheckBox cb = listaCheckbox.get(i); +// String search = cb.getText().toString(); +// if (!search.toLowerCase().contains(match.toLowerCase())) { +// cb.setChecked(false); +// ll.removeView(cb); +// } +// } +// } + //else{ + //} + //Log.d("my_debug", "after TEXT CHANGED"); + + } + }); + + ArrayList filterItems = null; + if( j >= 0 ) { + filterItems = filterColumns.getFilterItems(j); + } + + Iterator it = wartosci.iterator(); + while( it.hasNext()){ + String val = it.next(); + cb = new CheckBox(ListActivity.this); + cb.setText(val); // todo + ll.addView(cb); + listaCheckbox.add(cb); + + if( filterItems != null && filterItems.indexOf(val) >= 0 ) { + cb.setChecked(true); + } + } + + +// cb = new CheckBox(ListActivity.this); +// cb.setText("wartosc 2"); // todo +// ll.addView(cb); + + + // filtr tekstowy + // EditText et = new EditText(ListActivity.this); + // ll.addView(et); + ScrollView sv = new ScrollView(this); + sv.setVerticalScrollBarEnabled(true); + ll.setOrientation(LinearLayout.VERTICAL); + sv.addView(ll); + + lDialog.addView(sv); + + + alertDialog.setView(lDialog); + // alertDialog.setPositiveButton("OK", new New_folder_onlick(et)); + alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int which) { + + int bSortASC = 0; + String sortCol = ""; + ArrayList filterItems = new ArrayList(); + + if( rbRosnaco.isChecked()){ + bSortASC = 1; +// sortCol = code; + }else if( rbMalejaco.isChecked()){ + bSortASC = -1; + }else if( rbBezSortowania.isChecked()){ + bSortASC = 0; + } + sortCol = code; + + + for( int i=0; i< listaCheckbox.size(); i++){ + CheckBox cb = listaCheckbox.get(i); + if( cb.isChecked()){ + filterItems.add(cb.getText().toString()); + } + } + + int j = filterColumns.getIndexOfCode(sortCol); //sortColArr.indexOf(sortCol); + if( j >= 0 ) { + filterColumns.setColumn(j, sortCol, bSortASC, filterItems); + } + else { + filterColumns.addColumn(sortCol, bSortASC, filterItems); + Log.d("my_debug", "addRow, filterColumns: "+filterColumns); + } + + dialog.dismiss(); + wyswietlListe(); + + } + }); + + alertDialog.setNegativeButton("Anuluj", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int which) { +// int j = sortColArr.indexOf(code); //DedalHelper.findInArrayList(sortColArr, code); +// if( j >= 0 ) { +// filterItemsArr.set(j, new ArrayList()); +// bSortASCArr.set(j, 0); +// sortColArr.set(j, ""); +// } + + //filterItems = new ArrayList(); + dialog.dismiss(); + wyswietlListe(); + } + }); + alertDialog.show(); + + } + + + String getFormatedValue( JSONObject jZlecenie, String kod) throws JSONException{ + String ret = null; + if( kod.equals("tworca")){ + ret = jZlecenie.getString("tworca_login");//id_tworca + }else if( kod.equals("inspektor")){ + ret = jZlecenie.getString("inspektor_login"); + }else if( kod.equals("info_alert")){ + ret = jZlecenie.getString("data_alert"); + }else if( kod.equals("nr_sprawy-link")){ + ret = jZlecenie.getString("nr_sprawy"); + }else if( kod.equals("status")){ + ret = DedalHelper.getStatusDesc(jZlecenie.getString("status")); + }else if( kod.startsWith("data_")){ + String s = jZlecenie.getString(kod); + if( s.length()>=10){ + String d = jZlecenie.getString(kod).substring(0, 10); + ret = d; + }else{ + ret = s; + } +// +// }else if( kod.equals("")){ +// + }else{ + if( !jZlecenie.isNull(kod)){ + ret = jZlecenie.getString(kod); + } + } + return ret; + } + + private Set wczytajWartosciKolumny(String code) { + JSONObject jZlecenia; + Set ret = new TreeSet(); + + int j = filterColumns.getIndexOfCode(code); + if( j < 0 ) { + j = filterColumns.getSize(); + } + + try { + jZlecenia = new JSONObject(jProfil.getString("zlecenia")); + Iterator keys = jZlecenia.keys(); + while (keys.hasNext()) { + String id = (String) keys.next(); + JSONObject jZlecenie = jZlecenia.getJSONObject(id); + + if( j > 0 && !checkIfSearchMatchInternal(jZlecenie, j) ) { + continue; + } + + String val;// = jZlecenie.getString(code); + val = getFormatedValue ( jZlecenie, code); + + if( val != null){ + ret.add(val); + } + } + + } catch (JSONException e) { + Log.e(LOG, "", e); + } + + return ret; + } + + private boolean checkIfSearchMatchInternal(JSONObject jZlecenie) { + return checkIfSearchMatchInternal(jZlecenie, 0); + } + + private boolean checkIfSearchMatchInternal(JSONObject jZlecenie, int columnLimit) { // jeśli column Limit == 0 to wyłączenie limitu + + if( filterColumns.getSize() > 0 ) { + for( int i = 0 ; i < filterColumns.getSize() ; i++ ) { + if( columnLimit > 0 && i >= columnLimit ) { + break; + } + + ArrayList filterItems = filterColumns.getFilterItems(i); + String sortCol = filterColumns.getSortCol(i); + + if (filterItems.size() > 0) { + try { + String w = getFormatedValue(jZlecenie, sortCol); + if (!filterItems.contains(w)) { + return false; + } + } catch (JSONException e) { + Log.e(LOG, "", e); + } + } + } + } + return true; + } + + private boolean checkIfSearchMatch(JSONObject jZlecenie) { + // TODO Auto-generated method stub + //String search = etSearch.getText().toString().trim(); + + + if ( !checkIfSearchMatchInternal(jZlecenie) ) { + return false; + } + +// if( filterItemsArr.size() > 0 ) { +// +// for( int i = 0 ; i < filterItemsArr.size() ; i++ ) { +// ArrayList filterItems = filterItemsArr.get(i); +// String sortCol = sortColArr.get(i); +// +// if (filterItems.size() > 0) { +// try { +// String w = getFormatedValue(jZlecenie, sortCol); //jZlecenie.getString(sortCol); +// if (!filterItems.contains(w)) { +// return false; +// } +// } catch (JSONException e) { +// Log.e(LOG, "", e); +// } +// } +// } +// } + + /* + if( filterItems.size()>0){ + try { + String w = getFormatedValue(jZlecenie, sortCol); //jZlecenie.getString(sortCol); + if( !filterItems.contains(w)){ + return false; + } + } catch (JSONException e) { + Log.e(LOG, "", e); + } + + } + */ + + + if( search.length()>0){ + String id; + try { + id = jZlecenie.getString("id_zlecenia"); + File file = new File(prefs.getString("dir", "") + "/baza/" + id + ".json"); + + //TODO: zmienic, optymalizacja, indeksy, nie wczytywac obiektu + String sJson = DedalHelper.getFileContent(file.getAbsolutePath()); + + if( sJson!= null && sJson.length()>0 && sJson.toLowerCase().contains(search.toLowerCase())){ + return true; + } + + } catch (JSONException e) { + Log.e(LOG, "", e); + } + return false; + + }else + return true; + } + + private boolean checkIfInSelectedFolder(JSONObject jZlecenie) { + + if( id_folder > 0){ + String id; + try { + if( jZlecenie.has("id_folder") ) { + if( jZlecenie.getInt("id_folder") == id_folder) { + return true; + } + } + + } catch (JSONException e) { + Log.e(LOG, "", e); + } + return false; + + } + else if( id_folder == 0 ) { + try { + if( !jZlecenie.has("id_folder") || jZlecenie.getString("id_folder").equals("null") ) { + return true; + } + + + } catch (JSONException e) { + Log.e(LOG, "", e); + } + return false; + } + else + return true; + + + + } + + public static final int SHOW_PREFERENCES = 1; + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.list, menu); + return true; + } + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // TODO Auto-generated method stub + //return super.onOptionsItemSelected(item); + // swithc item.getItemId() + Intent i = new Intent(this, getPreferActivity()); + startActivityForResult(i, SHOW_PREFERENCES); + return true; + } + protected Class getPreferActivity() { + return PreferActivity.class; + } + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + // TODO Auto-generated method stub + super.onActivityResult(requestCode, resultCode, data); + + if (requestCode == REQUEST_MANAGE_ALL_FILES) { + // powrót z ekranu ustawień uprawnienia "Zarządzanie wszystkimi plikami" + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + if (Environment.isExternalStorageManager()) { + Toast.makeText(this, "Uprawnienie do zarządzania plikami przyznane.", Toast.LENGTH_SHORT).show(); + // zainicjalizuj UI jeśli jeszcze nie było + setupUIAndLogic(); + // i odśwież listę + wyswietlListe(); + } else { + Toast.makeText(this, "Brak wymaganego uprawnienia do plików. Aplikacja nie będzie działać poprawnie.", Toast.LENGTH_LONG).show(); + } + } + return; + } + + if( requestCode == SHOW_PREFERENCES){ + if( resultCode == Activity.RESULT_OK){ + + Context context = getApplicationContext(); + prefs = PreferenceManager.getDefaultSharedPreferences(context); + Log.setFileName(prefs.getString("dir", "")); + Log.setEH(); + Log.d(LOG,"Pomyslne zapisanie ustawien. hostnPath=" + prefs.getString("hostName", "")); + Intent service = new Intent(context, DedalService.class); + context.stopService(service); + context.startService(service); + } + } + } + + @Override + protected void onDestroy() { + // TODO Auto-generated method stub + super.onDestroy(); + names = null; + gps.stopUsingGPS(); + Log.d(LOG, "wylaczenie GPS'a"); + rlat.interrupt(); + Log.d("my_debug", "ondestroy"); + //onDestroyD(this); + } + public static void onDestroyD(Activity activity) { + View rootView = null; + Log.d(LOG, "niszczenie activity"); + try { + rootView = ((ViewGroup) activity.findViewById(android.R.id.content)) + .getChildAt(0); + } catch (Exception e) { + Log.d( LOG, "Cannot find root view to call unbindDrawables on"); + } + + if (rootView != null) { + Log.d(LOG,"unbindDrawables"); + unbindDrawables(rootView); + } + System.gc(); + Runtime.getRuntime().gc(); + } + + /** + * Utility method to unbind drawables when an activity is destroyed. This + * ensures the drawables can be garbage collected. + */ + public static void unbindDrawables(View view) { + if (view.getBackground() != null) { + view.getBackground().setCallback(null); + } + + if (view instanceof ViewGroup) { + for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { + unbindDrawables(((ViewGroup) view).getChildAt(i)); + } + + try { + // AdapterView objects do not support the removeAllViews method + if (!(view instanceof AdapterView)) { + ((ViewGroup) view).removeAllViews(); + } + } catch (Exception e) { + Log.d(LOG, "Ignore Exception in unbindDrawables"); + } + }else{ +// try +// { +// //view.setBackgroundDrawable(null); +// } +// catch(Exception e) +// { +// } + + try + { + if( view instanceof ImageView){ + ImageView imageView = (ImageView)view; + // imageView.setImageDrawable(null); + // imageView.setBackgroundDrawable(null); + //imageView.destroyDrawingCache(); + + BitmapDrawable bd = (BitmapDrawable)imageView.getDrawable(); + Bitmap bmp = bd.getBitmap(); + bmp.recycle(); + Log.d(LOG, "czyszczenie bitmapy"); + + } + } + catch(Exception e) + { + } + } + } + + private class FilterColumns { + private ArrayList sortColArr = new ArrayList(); + private ArrayList bSortASCArr = new ArrayList(); + private ArrayList> filterItemsArr = new ArrayList>(); + + public FilterColumns() { + this.sortColArr = new ArrayList(); + this.bSortASCArr = new ArrayList(); + this.filterItemsArr = new ArrayList>(); + } + public FilterColumns(ArrayList sortColArr, ArrayList bSortASCArr, ArrayList> filterItemsArr) { + this.sortColArr = sortColArr; + this.bSortASCArr = bSortASCArr; + this.filterItemsArr = filterItemsArr; + } + + /////////////// + public void reset() { + sortColArr = new ArrayList(); + bSortASCArr = new ArrayList(); + filterItemsArr = new ArrayList>(); + } + public int getIndexOfCode( String code ) { + return sortColArr.indexOf(code); + } + public int getSize() { + return sortColArr.size(); + } + + // set and add elements + public void addColumn( String sortCol, int bSortAsc, ArrayList filterItems) { + sortColArr.add(sortCol); + bSortASCArr.add(bSortAsc); + filterItemsArr.add(filterItems); + } + public boolean setColumn( int index, String sortCol, int bSortAsc, ArrayList filterItems) { + if( index >= 0 && index < sortColArr.size() ) { + sortColArr.set(index, sortCol); + bSortASCArr.set(index, bSortAsc); + filterItemsArr.set(index, filterItems); + + return true; + } + return false; + } + + // get element from index + public String getSortCol(int index) { + if( index < sortColArr.size() ) { + return sortColArr.get(index); + } + return null; + } + public Integer getBSortASC(int index) { + if( index < bSortASCArr.size()) { + return bSortASCArr.get(index); + } + return null; + } + public ArrayList getFilterItems(int index) { + if( index < filterItemsArr.size() ) { + return filterItemsArr.get(index); + } + return null; + } + + // return just properties + public ArrayList getSortColArr() { + return sortColArr; + } + public ArrayList getBSortASCArr() { + return bSortASCArr; + } + public ArrayList> getFilterItemsArr() { + return filterItemsArr; + } + + @Override + public String toString(){ + return "sortColArr: "+sortColArr+", bSortASCArr: "+bSortASCArr+", filterItemsArr"+filterItemsArr; + } + } + + ///////// +// private class ThreadCheckListaProfil implements Runnable { +// +// +// } + //////////////// +} diff --git a/app/src/main/java/com/likesoft/mdedal/Log.java b/app/src/main/java/com/likesoft/mdedal/Log.java new file mode 100644 index 0000000..0bab55a --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/Log.java @@ -0,0 +1,179 @@ +package com.likesoft.mdedal; + +import android.os.AsyncTask; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.PrintWriter; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +public class Log { + + + + private static void log(final String lOG, String string) { + + AsyncTask fileLog = new AsyncTask(){ + @Override + protected Object doInBackground(Object[] objects) { + logRow(objects[0].toString(), objects[1].toString()); + return null; + } + }; + fileLog.execute(lOG, string); + } + private static void logRow(String lOG, String string) { + + if( fileName != null){ + PrintWriter pw; + try { + Date d = new Date(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd"); + String fName = fileName+"/rt_"+sdf.format(d)+".log"; + File f = new File(fName); + if( !f.exists()){ + // new date, check if old should be sent to server + File dir = new File( fileName); + String[] fpliki = dir.list(new FilenameFilter(){ + + @Override + public boolean accept(File dir, String filename) { + // TODO Auto-generated method stub + return filename.startsWith("rt_"); + }}); + File up = new File(fileName +"/upload/log_file"); + if( !up.isDirectory()){ + up.mkdirs(); + } + if( fpliki != null ) { + for (int i = 0; i < fpliki.length; i++) { + File fi = new File(fileName + "/" + fpliki[i]); + String fi_name = fi.getName(); + + if ("rt_2014_05_25.log".compareTo(fi_name) > 0) { //create_date < "2014-05-20" ) { + fi.delete(); + } else { + Log.zip(fi.getAbsolutePath(), fi.getAbsolutePath() + ".zip"); + File fz = new File(fi.getAbsolutePath() + ".zip"); + File newF = new File(up.getAbsoluteFile() + "/" + fpliki[i] + ".zip"); + + if( fz != null && fz.exists() ) { + fz.renameTo(newF); + fi.delete(); + } + } + } + } + f.createNewFile(); + } + pw = new PrintWriter( + new FileWriter(fName, true)); + String prefix = ""; + //Date d = new Date(); + sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + prefix = sdf.format(d) + ":"; + pw.write(prefix + lOG + ":" + string+ "\n"); + pw.flush(); + pw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + } + public static void d(String tag, String msg){ + if(BuildConfig.DEBUG) { + android.util.Log.d(tag, msg); + StackTraceElement st = new Exception().getStackTrace()[1]; + log(tag, "DEBUG:" + st.getClassName() + ":" + st.getMethodName() + "(" + st.getLineNumber() + "):" + msg); + } + } + + public static void d(String tag, String msg, Throwable tr){ + if(BuildConfig.DEBUG) { + android.util.Log.d(tag, msg, tr); + log(tag, "DEBUG:" + msg + android.util.Log.getStackTraceString(tr)); + } + } + public static void e(String tag, String msg ){ + { + android.util.Log.e(tag, msg); + } + log(tag, "ERROR:" + msg); + } + public static void e(String tag, String msg, Throwable tr){ + { + android.util.Log.e(tag, msg, tr); + } + log(tag, "ERROR:" + msg + android.util.Log.getStackTraceString(tr)); + } + public static String fileName = null; + public static void setFileName( String dir){ + fileName = dir;// + "/rt.log"; + } + public static void setEH(){ + if( fileName == null){ + return; + } + Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { + @Override + public void uncaughtException(Thread thread, Throwable ex) { + + PrintWriter pw; + try { + Date d = new Date(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd"); + pw = new PrintWriter( + new FileWriter(fileName+"/rt_"+sdf.format(d)+".log", true)); + pw.write("uncaughtException\n"); + ex.printStackTrace(pw); + pw.flush(); + pw.close(); + ex.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + }); + } + + + public static void zip(String _file, String _zipFile) { + try { + BufferedInputStream origin = null; + FileOutputStream dest = new FileOutputStream(_zipFile); + + ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); + + int BUFFER = 1024; + byte data[] = new byte[BUFFER]; + + //for(int i=0; i < _files.length; i++) { + //Log.d("Compress", "Adding: " + _file); + FileInputStream fi = new FileInputStream(_file); + origin = new BufferedInputStream(fi, BUFFER); + ZipEntry entry = new ZipEntry(_file.substring(_file.lastIndexOf("/") + 1)); + out.putNextEntry(entry); + int count; + while ((count = origin.read(data, 0, BUFFER)) != -1) { + out.write(data, 0, count); + } + origin.close(); + //} + + out.close(); + } catch(Exception e) { + e.printStackTrace(); + } + + } +} diff --git a/app/src/main/java/com/likesoft/mdedal/MainActivity.java b/app/src/main/java/com/likesoft/mdedal/MainActivity.java new file mode 100644 index 0000000..6c7de82 --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/MainActivity.java @@ -0,0 +1,1373 @@ +package com.likesoft.mdedal; + +import android.Manifest; +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.Color; +import androidx.exifinterface.media.ExifInterface; +import android.net.Uri; +import android.os.Bundle; +import android.os.StrictMode; +import android.os.Build; +import android.preference.PreferenceManager; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +import android.telephony.TelephonyManager; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.ViewGroup; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.HorizontalScrollView; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.Spinner; +import android.widget.TableLayout; +import android.widget.TextView; +import android.widget.Toast; + +//import com.likesoft.mdedaltest.R; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; + +//import android.util.Log; + +//@SuppressLint("UseSparseArrays") +public class MainActivity extends DedalActivity { + + + private final class MyCreateLayout implements Runnable { + + JSONArray jKolumny; + TableLayout tl; + ArrayList aM; + protected LinearLayout ll; + + public MyCreateLayout(LinearLayout _ll) { + + ll = _ll; + } + + @Override + public void run() { + wyswietl_zlecenie(ll); + } + } + + + GPSTracker gps = null; + String id_zlecenia = ""; + //Thread t; + Boolean stop_thread = false; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + +// if(BuildConfig.DEBUG) +// StrictMode.enableDefaults(); + //lastId = 1000000; + if(BuildConfig.DEBUG){ + StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() + // .detectDiskReads() + // .detectDiskWrites() + .detectNetwork() // or .detectAll() for all detectable problems + .penaltyLog() + .build()); + StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() + .detectLeakedSqlLiteObjects() + //.detectLeakedClosableObjects() + .penaltyLog() + // .penaltyDeath() + .build()); + } + + res = getResources(); + + Context context = getApplicationContext(); + prefs = PreferenceManager.getDefaultSharedPreferences(context); + bTablet = prefs.getBoolean("tablet", false); + + Log.setFileName(prefs.getString("dir", "")); + Log.setEH(); + + Uri u = getIntent().getData(); + + gps = ListActivity.gps; + //if( gps != null ) { + try { + gps.getLocation(); + } catch (NullPointerException e) { + Log.e(LOG, "gps is null", e); + } + // setContentView(R.layout.activity_main); + +// RelativeLayout rl = new RelativeLayout(this); + LinearLayout rl = new LinearLayout(this); + // rl.setMinimumWidth(this.getWindow().getAttributes().width); + +// int x = this.getWindow().getAttributes().width; +// Log.d("my_debug", "szerokość ekranu MainActivity: "+ x); + + rl.setOrientation(LinearLayout.VERTICAL); + rl.setBackgroundColor(Color.WHITE); + // rl.setPadding(5, 1, 5, 1); + + //ArrayList values = new ArrayList(); + //Log.d("my_debug", "aaaa1"); + boolean bModified = false; + try { + + String pathName = u.getPath(); + String pathMod = pathName.replace(".json", ".mod"); + File fMod = new File(pathMod); + if (fMod.exists() && fMod.length() > 0) { + + pathName = pathMod; + bModified = true; + } + + File fJson = new File(pathName); + if (!fJson.exists()) { + Bundle extras = getIntent().getExtras(); + String filename = extras.getString("filename"); + id_zlecenia = filename.substring(0, filename.length() - 5); + Log.d("my_debug", "filename: " + filename); + Log.d("my_debug", "id_zlecenia: " + id_zlecenia); + File f_queue = new File(prefs.getString("dir", "") + "/queue/" + id_zlecenia); + + File d_queue_prio = new File(prefs.getString("dir", "") + "/queue_prio"); + if (!d_queue_prio.isDirectory()) { + d_queue_prio.mkdirs(); + } + File f_queue_prio = new File(prefs.getString("dir", "") + "/queue_prio/" + id_zlecenia); + if (f_queue.exists()) { + f_queue.renameTo(f_queue_prio); + } + else { + f_queue_prio.createNewFile(); + } + + // wystartuj/obudz serwis + Intent service = new Intent(context, DedalService.class); + context.startService(service); + + Thread t = new Thread(new Runnable() { + @Override + public void run() { + // TODO Auto-generated method stub + while (!stop_thread) { + + try { + Thread.sleep(500); + File f_queue_prio = new File(prefs.getString("dir", "") + "/queue_prio/" + id_zlecenia); + if (!f_queue_prio.exists()) { + Log.d("my_debug", "just downloaded: " + id_zlecenia); + reload(); + break; + } + + } catch (InterruptedException e) { + // TODO Auto-generated catch block + Log.e("my_debug", "", e); + } + } + } + }); + t.start(); + + AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); + alertDialog.setTitle("Pobieranie zlecenia"); + alertDialog.setMessage(res.getString(R.string.trwa_pobieranie_zlecenia)); + alertDialog.setPositiveButton("Wróć na listę zleceń", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + + stop_thread = true; + //t.stop(); + finish(); + } + }); + + alertDialog.show(); + return; + + } + + String sJson = DedalHelper.getFileContent(pathName); + js = new JSONObject(sJson);//fs.read(buffer)); + + params = js.getJSONObject("param"); + m_id = params.getString("id_zlecenia"); + //id_zlecenia = m_id; + String s = "Zlecenie nr: " + m_id; + if (!params.isNull("nazwa_klienta")) + s += " " + params.getString("nazwa_klienta"); + s += " " + params.getString("opis_szablonu"); + this.setTitle(s); + + } catch (FileNotFoundException e1) { + e1.printStackTrace(); + } catch (JSONException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + create_user_folders_arrays(); + + wyswietlNaglowek(rl); + if (bModified) { + llNaglowek.setBackgroundColor(Color.parseColor("#EBA0DD")); + } + + sw = new ScrollView(this); + + + HorizontalScrollView hs = new HorizontalScrollView(this); + rl.addView(sw); + sw.addView(hs); + +// rl.addView(hs); +// hs.addView(sw); + + LinearLayout ll = new LinearLayout(this); + ll.setId(View.generateViewId()); + ll.setOrientation(LinearLayout.VERTICAL); + ll.setPadding(20, 5, 5, 5); + //hs.addView(ll); + hs.addView(ll); + + int xx = this.getWindowManager().getDefaultDisplay().getWidth(); //getRealSize(p); + Log.d("my_debug", "szerokość ekranureal x: = " + xx); + ll.setMinimumWidth(xx); + + // zamiana na wątek: + //wyswietl_zlecenie(ll); + MyCreateLayout mcl = new MyCreateLayout(ll); + ll.post(mcl); +// Thread wt = new Thread( mcl); +// wt.start(); + + + setContentView(rl); +// rl.setDescendantFocusability(false); +// rl.requestFocus(); + rl.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); + rl.setFocusableInTouchMode(true); + + if (supportOnLoadReferences != null) { + supporRadioRef(supportOnLoadReferences, View.GONE); + } + + //temp +// sw.post(new Runnable() { +// @Override +// public void run() { +// Log.d("my_debug", "set set scrollTo, run: " + scrollTo); +// //int scrollX = sw.getScrollX(); +// sw.scrollTo(0, 200); +// //sw.scrollBy(0, scrollTo); +// //sw.fullScroll(ScrollView.FOCUS_DOWN); +// } +// }); + + } + + private void wyswietl_zlecenie(LinearLayout ll) { + try { + + first_foto_displayed = false; + + JSONObject pola = js.getJSONObject("pola"); + // for( int i=0; i aM = new ArrayList(); + while (k.hasNext()) { + String key = (String) k.next(); + JSONObject jo = pola.getJSONObject(key); + aM.add(jo); + } + sortujKolejnosc(aM); + + boolean enabled = true; + + //Log.d("my_debug", "STATUS: "+params.getString(STRUCT_STATUS)); + if (params.getString(STRUCT_STATUS).equals("wykonane_zaak") || + params.getString(STRUCT_STATUS).equals("wykonane")) { + enabled = false; + //Log.d("my_debug", "enable: false"); + } + Log.d("STATUS: ", params.getString(STRUCT_STATUS)); + + for (int z = 0; z < aM.size(); z++) { + JSONObject jo = (JSONObject) aM.get(z); + find_powtarzalne(jo, 0); + wyswietlPole(ll, jo, true, enabled); + //wyswietlPole(ll, jo); + } + + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NullPointerException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + private void create_user_folders_arrays() { + File dLista = new File(prefs.getString("dir", "") + "/baza/lista.profil"); + if (dLista.isFile()) { + + folderNazwy = new ArrayList(); + folderIds = new ArrayList(); + folderNazwy.add("Brak folderu"); + folderIds.add(0); + try { + String sJson = DedalHelper.getFileContent(dLista.getAbsolutePath()); + JSONObject jFile = new JSONObject(sJson); + + //JSONObject jProfiles = jFile.getJSONObject("profile"); + if (jFile.get("foldery") != null) { + JSONObject jFolders = jFile.getJSONObject("foldery"); + Iterator pKeys2 = jFolders.keys(); + + while (pKeys2.hasNext()) { + String idFolder = (String) pKeys2.next(); + JSONObject jFolder = jFolders.getJSONObject(idFolder); + //Log.d("my_debug","nazwa1: "+jFolder.getString("nazwa")); + folderNazwy.add(jFolder.getString("nazwa")); + folderIds.add(jFolder.getInt("id_folder")); + } + } + } catch (JSONException e) { + Log.e(LOG, e.getMessage()); + } + + } + + } + +// @Override +// protected void onResume() { +// super.onResume(); +// //autoscroll +// Log.d("my_debug", "set set scrollTo: " + scrollTo); +// //if (scrollTo > 0) { +// +// sw.post(new Runnable() { +// @Override +// public void run() { +// Log.d("my_debug", "set set scrollTo, run: " + scrollTo); +// sw.scrollTo(0, 1000); +// } +// }); +// // } +// } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + // TODO Auto-generated method stub + super.onActivityResult(requestCode, resultCode, data); + + + if (requestCode == REQUEST_CODE) { + + Log.d("my_debug", "set set scrollTo: " + scrollTo); + if (scrollTo > 0) { + Log.d("my_debug", "set set scrollTo, run: " + scrollTo); + sw.scrollTo(0, scrollTo); +// sw.post(new Runnable() { +// @Override +// public void run() { +// Log.d("my_debug", "set set scrollTo, run: " + scrollTo); +// //int scrollX = sw.getScrollX(); +// //sw.scrollTo(0, scrollTo); +// //sw.scrollBy(0, scrollTo); +// //sw.fullScroll(ScrollView.FOCUS_DOWN); +// } +// }); + } + + if (data.hasExtra("id")) { + String result = "Object ID=" + data.getExtras().getString("id"); + if (result != null && result.length() > 0) { + Toast.makeText(this, result, Toast.LENGTH_SHORT).show(); + } + } + if (data.hasExtra("tmpName")) { + String tmpName = data.getExtras().getString("tmpName"); + File tmp = new File(tmpName); + if (tmp.exists()) tmp.delete(); + } + /* + if( !fcameraOrig.exists()){ + MainActivity.this.reload(); + return; + }*/ + if (data.hasExtra("json") && data.hasExtra("id")) { + // check if radio, find parent to set up value + try { + + String sJson = DedalHelper.getFileContent(prefs.getString("dir", "") + "/baza/" + m_id + ".mod"); + js = new JSONObject(sJson);//fs.read(buffer)); + + JSONObject jo = find_element_from_Array(js, data.getExtras().getString("id")); //todo check if not null + if (TYPE_RADIOBUTTON.equals(jo.getString(STRUCT_TYP_DANYCH))) { + // find parent + String parent = jo.getString("parent"); + Log.d("my_debug", "szukanie parenta" + parent);// + JSONObject jParent = find_element_from_Array(js, parent); + if (jParent != null && TYPE_RADIOLISTA.equals(jParent.getString(STRUCT_TYP_DANYCH))) { + jParent.put(STRUCT_WARTOSC, jo.getInt("id_wiersz_szablonu")); + } + } + // stopAutozapis(); + autoZapisStop = false; + mod_json_files(false); + + setModified(); + //MainActivity.this.reload(); + return; + + } catch (JSONException e) { + e.printStackTrace(); + } + + } + + } + if (requestCode == TAKE_PICTURE) { + //1. convert size to 800x600 + //2. save to upload folder + Log.d(LOG, m_id + "foto_kod zdjecia: " + foto_kod + ", foto_name:" + foto_name); + + ExifInterface exifOrig = null; + File fcameraOrig = new File(prefs.getString("dir", "") + "/mDedalCam/" + foto_name); + + if (!fcameraOrig.exists()) { + MainActivity.this.reload(); + return; + } + + File fcamera = new File(prefs.getString("dir", "") + "/mDedalCam/" + foto_name + ".small"); + try { + exifOrig = new ExifInterface(fcameraOrig.getCanonicalPath()); + } catch (IOException e2) { + // TODO Auto-generated catch block + Log.e(LOG, "exif", e2); + } + // resize bitmap: + Bitmap bitmap = BitmapFactory.decodeFile(fcameraOrig.getAbsolutePath()); + if (bitmap != null) { + int origWidth = bitmap.getWidth(); + int origHeight = bitmap.getHeight(); + + final int destWidth = 2048;// or the width you need + + if (origWidth > destWidth) { + // picture is wider than we want it, we calculate + // its target height + int destHeight = origHeight + / (origWidth / destWidth); + // we create an scaled bitmap so it reduces the + // image, not just trim it + + Bitmap bitmapScalled = Bitmap.createScaledBitmap(bitmap, + destWidth, destHeight, false); + + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + // compress to the format you want, JPEG, PNG... + // 70 is the 0-100 quality percentage + bitmapScalled.compress(Bitmap.CompressFormat.JPEG, 70, outStream); + // we save the file, at least until we have made use of it +// File f = new File(Environment.getExternalStorageDirectory() +// + File.separator + "test.jpg"); +// f.createNewFile(); + //write the bytes in file + FileOutputStream fo; + try { + fo = new FileOutputStream(fcamera); + fo.write(outStream.toByteArray()); + // remember close de FileOutput + fo.close(); + outStream.close(); + } catch (FileNotFoundException e) { + Log.e(LOG, "nie znaleziono pliku", e); + } catch (IOException e) { + Log.e(LOG, "inny blad przy zapisywaniu zdjecia", e); + } + bitmapScalled.recycle(); + bitmap.recycle(); + } else { + fcamera = fcameraOrig; + } + } + + //add GPS to EXIF + try { + + ExifInterface exif = new ExifInterface(fcamera.getCanonicalPath()); + String x = exifOrig.getAttribute(ExifInterface.TAG_GPS_LATITUDE); + Log.d("GPS", "pozycja ze zdjecia x = " + x); + + + // check if GPS enabled + gps.getLocation(); + if (gps.canGetLocation()) { + double latitude = gps.getLatitude(); + double longitude = gps.getLongitude(); + exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE, "" + DedalHelper.decimalToDMS(latitude)); + exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, "" + DedalHelper.decimalToDMS(longitude)); + + if (!gps.isGPSEnabled) { + exif.setAttribute(ExifInterface.TAG_MAKE, "mDedal WiFI or GSM"); + } else { + exif.setAttribute(ExifInterface.TAG_MAKE, "mDedal GPS, SAT: " + gps.liczbaSatelitow); + + } + } else { + exif.setAttribute(ExifInterface.TAG_MAKE, "mDedal no GPS info"); + } + // przepisz atrybuty + if (exifOrig != null) { + exif.setAttribute(ExifInterface.TAG_MODEL, exifOrig.getAttribute(ExifInterface.TAG_MODEL)); + exif.setAttribute(ExifInterface.TAG_DATETIME, exifOrig.getAttribute(ExifInterface.TAG_DATETIME)); + exif.setAttribute(ExifInterface.TAG_ORIENTATION, exifOrig.getAttribute(ExifInterface.TAG_ORIENTATION)); + exif.setAttribute(ExifInterface.TAG_FLASH, exifOrig.getAttribute(ExifInterface.TAG_FLASH)); + exif.setAttribute("DateTimeOriginal", exifOrig.getAttribute(ExifInterface.TAG_DATETIME)); + exif.setAttribute("Software", "mDedal v. xxx"); + } + + exif.saveAttributes(); + + } catch (IOException e1) { + // TODO Auto-generated catch block + //e1.printStackTrace(); + Log.e(LOG, "", e1); + } catch (NullPointerException e1) { + // TODO Auto-generated catch block + //e1.printStackTrace(); + Log.e(LOG, "", e1); + } + + + File fDir = new File(prefs.getString("dir", "") + "/mDedal/" + m_id + "/" + foto_kod); + if (!fDir.isDirectory()) { + fDir.mkdirs(); + } + + File f = new File(prefs.getString("dir", "") + "/mDedal/" + m_id + "/" + foto_kod + "/" + foto_name); + //Environment.getDataDirectory(); + File fDstf = new File(prefs.getString("dir", "") + "/upload/" + m_id + "/" + foto_kod); + if (!fDstf.isDirectory()) { + fDstf.mkdirs(); + } + File fDst = new File(prefs.getString("dir", "") + "/upload/" + m_id + "/" + foto_kod + "/" + foto_name); + try { + DedalHelper.copyEncode(fcamera, f); + copy( f, fDst); + if( fcamera!=fcameraOrig) { + fcamera.delete(); + } + fcameraOrig.delete(); + + } catch (IOException e) { + Log.e(LOG, "nieudane kopiowanie zdjęcia", e); + } + wyswietlPytanieCzyNastepneZdjecie(foto_kod); + } + } + + @Override + public OnClickListener getZapisz_zmiany(JSONObject jo, String typ) { + return new Zapisz_zmiany(jo, typ); + } + @Override + protected void setModified(){ + llNaglowek.setBackgroundColor(Color.parseColor("#EBA0DD")); +// llNaglowek.setBackgroundResource(R.style.NaglowekNormal); + +// if( autoZapis == null ){ +// // dodaj button Wycofaj zmiany +// +// } + + + autoZapisStop = false; + startAutoZapis(); + } + + + public final class Zapisz_zmiany implements OnClickListener { + + //private LinearLayout ll; + private JSONObject jo; + private String typ; + + + public Zapisz_zmiany( JSONObject jo, String typ) { + //super(); + //this.ll = ll; + this.jo = jo; + this.typ = typ; + } + + @Override + public void onClick(final View v) { + //DedalActivity.this.findViewById(v.getId()); + //v.setEnabled(false); + String komunikat = ""; + // zapiszZmiany + try { + komunikat_obowiazkowe = ""; + komunikat_walidacja = ""; + + JSONObject pola = js.getJSONObject("pola"); + Iterator k = pola.keys(); + + while (k.hasNext()) { + String key = (String) k.next(); + JSONObject jo2 = pola.getJSONObject(key); + zapiszZmiany(jo2); + } + + if (!komunikat_obowiazkowe.equals("") || !komunikat_walidacja.equals("")) { + if (!komunikat_obowiazkowe.equals("")) { + komunikat = res.getString(R.string.walid_pola_obowiazkowe) + ": \n" + komunikat_obowiazkowe + "\n"; + Log.d("my_debug", "Nie wypełniłeś pól obowiązkowych: " + komunikat); + } + if (!komunikat_walidacja.equals("")) { + komunikat += "\n" + res.getString(R.string.walid_zle_wypelnione) + ": \n" + komunikat_walidacja + "\n"; + } + } + else { + + } + + /// GPS /// + + + //GPSTracker gps = new GPSTracker(MainActivity.this); + //if( gps != null ) { + try { + TelephonyManager telephonyManager; + telephonyManager = + (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); + + int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_PHONE_STATE); + + if (permissionCheck == PackageManager.PERMISSION_GRANTED) { + String imsistring = ""; + String mPhoneNumber = ""; + try { + if (Build.VERSION.SDK_INT < 29) { + imsistring = telephonyManager.getSubscriberId(); + mPhoneNumber = telephonyManager.getLine1Number(); + } + } catch (SecurityException ignored) { + } + + gps.getLocation(); + double latitude = gps.getLatitude(); + double longitude = gps.getLongitude(); + String isGPS = "" + gps.isGPSEnabled; + String imsi = imsistring + "T" + mPhoneNumber; + + JSONObject gps_json = new JSONObject(); + gps_json.put("latitude", latitude); + gps_json.put("longitude", longitude); + gps_json.put("isGPS", isGPS); + gps_json.put("imsi", imsi); + js.put("gps", gps_json); + } + + } catch (NullPointerException e) { + Log.e(LOG, "custom null exception", e); + } + /// END GPS /// + + if( typ.equals("zakoncz_wizyte") ) { + + if( komunikat.equals("") ) { // pola sÄ… dobrze wypeĹ‚nnione + AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); + alertDialog.setTitle( res.getString(R.string.zakanczanie_wizyty) ); + alertDialog.setMessage(res.getString(R.string.czy_zakonczyc_wizyte) ); + alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int which) { + try { + js.put("sub", "sub_end="+jo.getInt("id")); + jo.put(STRUCT_STATUS, "end"); + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + mod_json_files(true); + //DedalActivity.this.reload(); + finish(); + } + }); + alertDialog.setNegativeButton("Anuluj", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int which) { + mod_json_files(false); + dialog.dismiss(); + } + }); + alertDialog.show(); + } + else { // pola sÄ… Ĺşle wypeĹ‚nione + AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); + alertDialog.setTitle( res.getString(R.string.zakanczanie_wizyty) ); + alertDialog.setMessage(komunikat); + alertDialog.setPositiveButton("Anuluj", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int which) { + mod_json_files(false); + dialog.dismiss(); + } + }); + alertDialog.show(); + } + + } + if( typ.equals("zapisz_zmiany") ) { + + //Log.d("my_debug", "put sub: Zapisz zmiany"); + //DedalActivity.this.recreate(); + if( komunikat.equals("") ) { // pola sÄ… dobrze wypeĹ‚nnione + js.put("sub", "Zapisz zmiany"); + mod_json_files(true); + //DedalActivity.this.reload(); + finish(); + } + else { // pola sÄ… Ĺşle wypeĹ‚nione + AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); + alertDialog.setTitle( res.getString(R.string.wysylanie_do_centrum) ); + alertDialog.setMessage(komunikat); + alertDialog.setPositiveButton( res.getString(R.string.wyslij), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int which) { + try { + js.put("sub", "Zapisz zmiany"); + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + mod_json_files(true); + //dialog.dismiss(); + MainActivity.this.reload(); + //finish(); + } + }); + alertDialog.setNegativeButton("Anuluj", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int which) { + mod_json_files(false); + dialog.dismiss(); + } + }); + alertDialog.show(); + } + } + if( typ.equals("zapisz_i_zamknij_zlecenie") ) { + + if( komunikat.equals("") ) { // pola sÄ… dobrze wypeĹ‚nnione + + AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); + alertDialog.setTitle( res.getString(R.string.wysylanie_do_centrum) ); + + String message = res.getString(R.string.czy_wyslac_zlecenie); + + // jesli istnieja niezakonczone wizyty to wyswietl komunikat, z mozliwosia zamkniecia wizyt. + if( is_notend_intevention ) { + message = res.getString(R.string.wykryto_niezakonczone_wizyty); + + alertDialog.setNeutralButton(R.string.wyslij_i_zakoncz_wizyty, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int which) { + Log.d("my_debug", "wyslij i zakoncz wizyty"); + try { + js.put("sub_stat_acc", params.getString(STRUCT_STATUS)); + + //jo.put(STRUCT_STATUS, "end"); // przerobic + + js.put("sub", "Zapisz i zamknij zlecenie"); + if( params.getString(STRUCT_STATUS).equals("przydz_odeb") ) { + params.put(STRUCT_STATUS, "wykonane"); + } + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + mod_json_files(true); + //DedalActivity.this.reload(); + finish(); + } + }); + } + + alertDialog.setMessage( message ); + + + alertDialog.setPositiveButton( res.getString(R.string.wyslij) , new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int which) { + try { + js.put("sub", "Zapisz i zamknij zlecenie"); + if( params.getString(STRUCT_STATUS).equals("przydz_odeb") ) { + params.put(STRUCT_STATUS, "wykonane"); + } + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + mod_json_files(true); + //DedalActivity.this.reload(); + finish(); + } + }); + + + alertDialog.setNegativeButton("Anuluj", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int which) { + mod_json_files(false); + dialog.dismiss(); + } + }); + alertDialog.show(); + } + else { // pola sÄ… Ĺşle wypeĹ‚nione + AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); + alertDialog.setTitle( res.getString(R.string.wysylanie_do_centrum) ); + alertDialog.setMessage(komunikat); + alertDialog.setPositiveButton("Anuluj", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int which) { + mod_json_files(false); + dialog.dismiss(); + } + }); + alertDialog.show(); + } + + //ListActivity.class.(); + } + if( typ.equals("dodaj_wizyte") ) { + + //Log.d("my_debug", "put: sub_add="+jo.getInt("id")); + + AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); + alertDialog.setTitle("Dodawanie wizyty"); + alertDialog.setMessage( res.getString(R.string.czy_dodac_wizyte) ); + alertDialog.setPositiveButton("Tak", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int which) { + + //v.setEnabled(false); + try { + js.put("sub", "sub_add="+jo.getInt("id")); + jo.put("dodawanie_wizyty", "true"); + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + mod_json_files(true); + //DedalActivity.this.reload(); + finish(); + } + }); + alertDialog.setNegativeButton("Anuluj", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int which) { + //mod_json_files(false); + dialog.dismiss(); + } + }); + alertDialog.show(); + + //ListActivity.class.(); + } + + + + komunikat_obowiazkowe = ""; + komunikat_walidacja = ""; +// //zablokowanie pďż˝l po zakoďż˝czeniu +// JSONArray ja = jo.getJSONArray(STRUCT_CHILDS); +// if( ja!= null && ja.length()>0){ +// for ( int i=0; i0){ +// for ( int i=0; i 0) { + Button dokKollektoBtn = new Button(MainActivity.this); + dokKollektoBtn.setText("Dokumenty Kollekto"); + + dokKollektoBtn.setOnClickListener(new DokKollektoBtnListener(m_id, dkJson)); + ll.addView(dokKollektoBtn); + } + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + @Override + synchronized protected void mod_json_files(boolean mod_upload) { + FileOutputStream fos; + try { + //id_zlecenia + if( !mod_upload && autoZapisStop){ + return; // nie zapisuj, jak jest wylaczony. + } + File dst = saveToModFile(js); + + if( mod_upload ) { // jeďż˝li jest jakiďż˝ komunikat to znaczy ďż˝e pola sďż˝ ďż˝le wypeďż˝nione, nie moďż˝e to pďż˝j�� na serwer + + autoZapisStop = true; + if( autoZapis != null){ + autoZapis.interrupt(); + try { + autoZapis.join(2000); + } catch (InterruptedException e) { + Log.e("DedalActivity", "nie udalo sie zatrzymac autozapisu", e); + } + autoZapis = null; + } + + // delete original json + File jF = new File(prefs.getString("dir", "") + "/baza/" + m_id + ".json"); + jF.delete(); + copy( dst, jF); + + Date d = new Date(); + String genName = "upl_"+d.getTime() + ".mod"; + File dstDir = new File(prefs.getString("dir", "") + "/upload/"+m_id); + if( !dstDir.isDirectory()){ dstDir.mkdirs(); } + + // + + File fMod = new File(prefs.getString("dir", "") + "/upload/" + m_id + "/" + genName); + dst.renameTo(fMod); + + // wystartuj/obudz serwis + Context context = getApplicationContext(); + Intent service = new Intent(context, DedalService.class); + context.startService(service); + } + + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + @Override + protected void forceDoZapis(String key, String kod) { + if( autoZapis != null ){ + try { + autoZapisStop = true; + autoZapis.interrupt(); + autoZapis.join(); + } catch (InterruptedException e) { + Log.e(LOG, "", e); + } + doAutoZapis(); + try { + js.put(key, kod); + mod_json_files(true); + } catch (JSONException e) { + Log.e(LOG, "nieudany zapis zmian na serwer przed wywolanie nowego intentu", e); + } + } + } + + @Override + protected void onPause() { + // TODO Auto-generated method stub + super.onPause(); + if( autoZapis != null ){ + try { + autoZapisStop = true; + autoZapis.interrupt(); + autoZapis.join(); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + doAutoZapis(); + } + } + + + Thread autoZapis=null; + boolean autoZapisStop = false; + protected void startAutoZapis() { + if( autoZapis == null ){ + autoZapis = new Thread( new Runnable() { + @Override + public void run() { + // save to json.mod file + while( !autoZapisStop){ + runOnUiThread(new Runnable() { + @Override + public void run() { + doAutoZapis(); + } + }); + + try { + Thread.sleep(10000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + //e.printStackTrace(); + Log.d(LOG, "AutoZapis przerwany."); + break; + } + } + + } + }); + autoZapis.start(); + } + } + + @Override + protected void stopAutozapis() { + if( autoZapis != null ){ + try { + autoZapisStop = true; + autoZapis.interrupt(); + autoZapis.join(); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + doAutoZapis(); + } + } + + protected void doAutoZapis(){ + Log.d(LOG, "Auto zapis."); + JSONObject pola; + try { + pola = js.getJSONObject("pola"); + Iterator k = pola.keys(); + + while (k.hasNext()) { + String key = (String) k.next(); + JSONObject jo2 = pola.getJSONObject(key); + zapiszZmiany( jo2 ); + } + + } catch (JSONException e1) { + Log.e("DedalActivity", "nieudany zapiszZmiany", e1); + } + + mod_json_files(false); + + } + + public static void copy(File src, File dst) throws IOException { + InputStream in = new FileInputStream(src); + OutputStream out = new FileOutputStream(dst); + + // Transfer bytes from in to out + byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + in.close(); + out.close(); + } + + + protected int get_id_folder(String id_zlecenia_Zlecenie) { + int id_folder = -1; + + try { + File dLista = new File(prefs.getString("dir", "") + "/baza/lista.profil"); + if( dLista.isFile()){ + String sFile = DedalHelper.getFileContent(prefs.getString("dir", "") + "/baza/lista.profil"); + JSONObject jFile = new JSONObject(sFile); + JSONObject jProfiles = jFile.getJSONObject("profile"); + Iterator pKeys = jProfiles.keys(); + Boolean break_ = false; + + while( pKeys.hasNext()){ + String idProfilu = (String)pKeys.next(); + JSONObject jProfil = jProfiles.getJSONObject(idProfilu); + String s = jProfil.getString("zlecenia"); + if( s.equals("[]")){ + continue; + } + JSONObject jZlecenia = jProfil.getJSONObject("zlecenia"); + Iterator pKeys2 = jZlecenia.keys(); + while( pKeys2.hasNext() ){ + String id_zlecenia = (String)pKeys2.next(); + if ( id_zlecenia.equals( id_zlecenia_Zlecenie ) ) { + JSONObject jZlecenie = jZlecenia.getJSONObject(id_zlecenia); + if( jZlecenie.has("id_folder") ) { + if( jZlecenie.getString("id_folder").equals("null") ) { + id_folder = 0; + } + else { + id_folder = jZlecenie.getInt("id_folder"); + } + break_ = true; + break; + } + } + else { + continue; + } + } + if( break_ ) { + break; + } + } + } + } catch (JSONException e) { + e.printStackTrace(); +// } catch (FileNotFoundException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (IOException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); + } + return id_folder; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/likesoft/mdedal/MyXMLSerializer.java b/app/src/main/java/com/likesoft/mdedal/MyXMLSerializer.java new file mode 100644 index 0000000..459c73e --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/MyXMLSerializer.java @@ -0,0 +1,410 @@ +package com.likesoft.mdedal; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.Writer; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.xmlpull.v1.XmlSerializer; + +/* + * NOT USED CLASS + */ + +class MyXMLSerializer implements XmlSerializer{ + + private class MyXMLSerializerData { + public OutputStream m_os; + public boolean started; + + public MyXMLSerializerData(OutputStream m_os, boolean started) { + this.m_os = m_os; + this.started = started; + } + } + MyXMLSerializerData data = new MyXMLSerializerData(null, false); + + // dst = new File(getFilesDir().getAbsolutePath() + "/baza/" + genName); +// fos = new FileOutputStream(dst); +// XmlSerializer xmlSerializer = new MyXMLSerializer(); +// xmlSerializer.setOutput(fos, "UTF-8"); +// zapiszAsXML(js, xmlSerializer); +// fos.flush(); +// fos.close(); + + + //http://stackoverflow.com/questions/9869507/how-to-create-an-xml-using-xmlserializer-in-android-app + void zapiszAsXML(JSONObject jo, XmlSerializer xS, String m_id, JSONObject js){ + try { + xS.startDocument("UTF-8", true); + // xS.startDocument("UTF_8", true); + // xS.startDocument(Xml.Encoding.UTF_8, true); + //Xml.Encoding UTF_8 + // Xml.Encoding.UTF_8 + xS.startTag("", "zlecenia"); + xS.startTag("", "zlecenie"); + + xS.startTag("", "id_zlecenia"); + xS.text(m_id); + xS.endTag("", "id_zlecenia"); + + try { + xS.startTag("", "id_szablonu"); + JSONObject zlecenie_param = js.getJSONObject("param"); + xS.text(zlecenie_param.getString("id_szablonu")); + xS.endTag("", "id_szablonu"); + + JSONObject pola = js.getJSONObject("pola"); + ArrayList aM = new ArrayList(); + + //if() + // for( int i=0; i0){ + xS.startTag("", "childs"); + Iterator k = pola.keys(); + while (k.hasNext()) { + String key = (String) k.next(); + JSONObject joP = pola.getJSONObject(key); + aM.add(joP); + } + + sortujKolejnosc(aM); + + for( int z=0; z + } + private void zapiszPolaXML(JSONObject joP, XmlSerializer xS) { + // TODO Auto-generated method stub + + try { + xS.startTag("", "pole"); + xS.attribute("", "kod", joP.getString("kod")); + + xS.startTag("", "wartosc"); + + String typ = joP.getString("typ_danych"); + if( "radiolista".equals(typ)){ + JSONArray ja = joP.getJSONArray("childs"); + if( ja!= null && ja.length()>0){ + for ( int i=0; i0){ + xS.startTag("", "childs"); + for ( int i=0; i aM) { + Collections.sort(aM, new Comparator() { + @Override + public int compare(JSONObject lhs, JSONObject rhs) { + // TODO Auto-generated method stub + try { + if( lhs.getInt("kolejnosc") >(rhs.getInt("kolejnosc"))){ + return 1; + }else if( lhs.getInt("kolejnosc") < (rhs.getInt("kolejnosc"))){ + return -1; + }else{ + if( lhs.getInt("id") > (rhs.getInt("id"))) + return 1; + else if ( lhs.getInt("id") < (rhs.getInt("id"))) + return -1; + return 0; + } + } catch (JSONException e) { + // TODO Auto-generated catch block + //e.printStackTrace(); + } + return 0; + } + }); + } + + @Override + public void startDocument(String encoding, Boolean standalone) + throws IOException, IllegalArgumentException, + IllegalStateException { + // TODO Auto-generated method stub + data.m_os.write("".getBytes()); + } + + @Override + public XmlSerializer startTag(String namespace, String name) + throws IOException, IllegalArgumentException, + IllegalStateException { + // TODO Auto-generated method stub + if( data.started){ + data.m_os.write(">".getBytes()); + data.started = false; + } + StringBuffer b = new StringBuffer(); + b.append("<"); + b.append(name); + b.append(" "); + data.m_os.write(b.toString().getBytes()); + data.started = true; + return this; + } + + @Override + public XmlSerializer text(String text) throws IOException, + IllegalArgumentException, IllegalStateException { + // TODO Auto-generated method stub + if( data.started){ + data.m_os.write(">".getBytes()); + data.started = false; + } + data.m_os.write(text.getBytes()); + return this; + } + + @Override + public XmlSerializer attribute(String namespace, String name, + String value) throws IOException, IllegalArgumentException, + IllegalStateException { + StringBuffer b = new StringBuffer(); + b.append(name); + b.append("=\""); + b.append(value); + b.append("\" "); + data.m_os.write(b.toString().getBytes()); + return this; + } + + @Override + public XmlSerializer endTag(String namespace, String name) + throws IOException, IllegalArgumentException, + IllegalStateException { + if( data.started){ + data.m_os.write(">".getBytes()); + data.started = false; + } + StringBuffer b = new StringBuffer(); + b.append(""); + data.m_os.write(b.toString().getBytes()); + return this; + } + + + @Override + public void setOutput(OutputStream os, String encoding) + throws IOException, IllegalArgumentException, + IllegalStateException { + // TODO Auto-generated method stub + data.m_os = os; + } + + + + + + + + + + + + + + + + + @Override + public void cdsect(String text) throws IOException, + IllegalArgumentException, IllegalStateException { + // TODO Auto-generated method stub + + } + + @Override + public void comment(String text) throws IOException, + IllegalArgumentException, IllegalStateException { + // TODO Auto-generated method stub + + } + + @Override + public void docdecl(String text) throws IOException, + IllegalArgumentException, IllegalStateException { + // TODO Auto-generated method stub + + } + + @Override + public void endDocument() throws IOException, IllegalArgumentException, + IllegalStateException { + // TODO Auto-generated method stub + + } + + + @Override + public void entityRef(String text) throws IOException, + IllegalArgumentException, IllegalStateException { + // TODO Auto-generated method stub + + } + + @Override + public void flush() throws IOException { + // TODO Auto-generated method stub + + } + + @Override + public int getDepth() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public boolean getFeature(String name) { + // TODO Auto-generated method stub + return false; + } + + @Override + public String getName() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getNamespace() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getPrefix(String namespace, boolean generatePrefix) + throws IllegalArgumentException { + // TODO Auto-generated method stub + return null; + } + + @Override + public Object getProperty(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void ignorableWhitespace(String text) throws IOException, + IllegalArgumentException, IllegalStateException { + // TODO Auto-generated method stub + + } + + @Override + public void processingInstruction(String text) throws IOException, + IllegalArgumentException, IllegalStateException { + // TODO Auto-generated method stub + + } + + @Override + public void setFeature(String name, boolean state) + throws IllegalArgumentException, IllegalStateException { + // TODO Auto-generated method stub + + } + + @Override + public void setOutput(Writer writer) throws IOException, + IllegalArgumentException, IllegalStateException { + // TODO Auto-generated method stub + + } + + @Override + public void setPrefix(String prefix, String namespace) + throws IOException, IllegalArgumentException, + IllegalStateException { + // TODO Auto-generated method stub + + } + + @Override + public void setProperty(String name, Object value) + throws IllegalArgumentException, IllegalStateException { + // TODO Auto-generated method stub + + } + + @Override + public XmlSerializer text(char[] buf, int start, int len) + throws IOException, IllegalArgumentException, + IllegalStateException { + // TODO Auto-generated method stub + return null; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/likesoft/mdedal/PreferActivity.java b/app/src/main/java/com/likesoft/mdedal/PreferActivity.java new file mode 100644 index 0000000..86163e6 --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/PreferActivity.java @@ -0,0 +1,295 @@ +package com.likesoft.mdedal; + +import android.Manifest; +import android.content.Intent; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.os.Environment; +import android.preference.PreferenceManager; +import android.app.Activity; +import android.content.Context; +import android.content.SharedPreferences; +import android.content.SharedPreferences.Editor; +import android.provider.Settings; +import android.view.Menu; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.EditText; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; + +//import com.likesoft.mdedaltest.*; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import static com.likesoft.mdedal.ListActivity.LOG; + + +public class PreferActivity extends Activity { + + private static final int REQ_STORAGE_PERMISSION = 1001; + private static final int REQ_MANAGE_ALL_FILES = 2296; + + // EditText hostName; + EditText user; + EditText password; + EditText newpassword; +// CheckBox tablet; + // Spinner refresh; + //TextView version; + TextView textViewHostUrl; + + SharedPreferences prefs; + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_prefer); + // hostName = (EditText) findViewById(R.id.editTextHost); + user = (EditText) findViewById(R.id.editTextUser); + password = (EditText) findViewById(R.id.editTextPassword); + newpassword = (EditText) findViewById(R.id.editTextNewPassword); + // tablet = (CheckBox) findViewById(R.id.checkBoxTablet); + // refresh = (Spinner) findViewById(R.id.spinner_refresh); + //version = (TextView) findViewById(R.id.textViewVersion); + + //textViewHostUrl + textViewHostUrl = (TextView) findViewById(R.id.textViewHostUrl); + + PackageInfo pinfo; + try { + pinfo = getPackageManager().getPackageInfo(getPackageName(), 0); + //versionNumber = pinfo.versionCode; + String versionName = pinfo.versionName; + //version.setText("Wersja aplikacji: "+versionName); + setTitle("Logowanie - Wersja aplikacji: "+versionName); + } catch (PackageManager.NameNotFoundException e2) { + Log.e(LOG, "", e2); + } + + Context context = getApplicationContext(); + + prefs = PreferenceManager.getDefaultSharedPreferences(context); + updateUI(); + //Log.d("my_debug", "oncreate prefs"); + + Button ok = (Button)findViewById(R.id.buttonSave); + ok.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + // Zanim zapiszemy preferencje, upewnijmy się, że mamy dostęp do pamięci + if (!hasStorageAccess()) { + requestStorageAccess(); + Toast.makeText(PreferActivity.this, "Brak uprawnień do zapisu w pamięci. Przyznaj uprawnienie i spróbuj ponownie.", Toast.LENGTH_LONG).show(); + return; + } + if( newpassword.getText().toString().length()>0){ + savePreferences(); + new Thread( new Runnable() { + @Override + public void run() { + DedalHttpConnection con = new DedalHttpConnection(getApplicationContext()); + Map params_post = new HashMap(); + params_post.put("oldpass", password.getText().toString()); + params_post.put("pass1", newpassword.getText().toString()); + params_post.put("pass2", newpassword.getText().toString()); + String response = ""; + try{ + response = con.sendPost("public/mobi.php?page=login_change", params_post); + }catch (Exception e){ + Log.e( "BLAD ", "Bląd połączenia"); + } + if( response.contains("zmienione") ) { + //jeśli się powiodło: + // password.setText(newpassword.getText()); + Editor e = prefs.edit(); + e.putString("password", DedalHelper.encodeB64(newpassword.getText().toString())); + e.commit(); + Log.d("PASSWORD", "hasło zostało zmienione na: "+ newpassword.getText().toString()); + //savePreferences(); + + Button ok = (Button)findViewById(R.id.buttonSave); + ok.post(new Runnable() { + @Override + public void run() { + Toast.makeText(PreferActivity.this, "Hasło zmienione.", Toast.LENGTH_LONG); + PreferActivity.this.setResult(RESULT_OK); + finish(); + } + }); + } + else { + Log.d("PASSWORD", "problem ze zmianą hasła, response: " + response); + Toast.makeText(PreferActivity.this, "Problem ze zmianą hasła", Toast.LENGTH_LONG); + } + + } + }).start(); + }else { + savePreferences(); + PreferActivity.this.setResult(RESULT_OK); + finish(); + } + } + + + }); + } + + private boolean hasStorageAccess() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + return Environment.isExternalStorageManager(); + } else { + int write = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); + int read = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE); + return write == PackageManager.PERMISSION_GRANTED && read == PackageManager.PERMISSION_GRANTED; + } + } + + private void requestStorageAccess() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + try { + Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION); + intent.setData(Uri.parse("package:" + getPackageName())); + startActivityForResult(intent, REQ_MANAGE_ALL_FILES); + } catch (Exception ex) { + Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION); + startActivityForResult(intent, REQ_MANAGE_ALL_FILES); + } + } else { + ActivityCompat.requestPermissions(this, + new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, + REQ_STORAGE_PERMISSION); + } + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (requestCode == REQ_MANAGE_ALL_FILES) { + if (hasStorageAccess()) { + Toast.makeText(this, "Przyznano dostęp do plików.", Toast.LENGTH_SHORT).show(); + } else { + Toast.makeText(this, "Dostęp do plików nadal zablokowany.", Toast.LENGTH_LONG).show(); + } + } + } + + @Override + public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + if (requestCode == REQ_STORAGE_PERMISSION) { + boolean granted = true; + if (grantResults == null || grantResults.length == 0) granted = false; + for (int r : grantResults) { + if (r != PackageManager.PERMISSION_GRANTED) { granted = false; break; } + } + if (granted) { + Toast.makeText(this, "Uprawnienia do pamięci przyznane.", Toast.LENGTH_SHORT).show(); + } else { + Toast.makeText(this, "Odmówiono uprawnień do pamięci.", Toast.LENGTH_LONG).show(); + } + } + } + + public static void deleteFiles(String path) { + + File file = new File(path); + + if (file.exists()) { + String deleteCmd = "rm -r " + path; + Runtime runtime = Runtime.getRuntime(); + try { + runtime.exec(deleteCmd); + } catch (IOException e) { } + } + } + + void savePreferences() { + // TODO Auto-generated method stub + + String currentHost = prefs.getString("hostName", "https://dedal.eos-ksi.pl"); + + Editor e = prefs.edit(); + e.putString("hostName", currentHost); +// e.putBoolean("tablet", tablet.isChecked()); + String login = user.getText().toString().trim(); + + if( login.contains("@")){ + String loginTable[] = login.split("@"); + e.putString("user", loginTable[0]); + if("reset".equals(loginTable[1]) ){ + e.putString("certSerialNumber", ""); + deleteFiles(Environment.getExternalStorageDirectory()+ "/dedal/"); + }else { + if( loginTable[1].startsWith("http")) { + e.putString("hostName", loginTable[1]); + } + } + login = loginTable[0]; + }else { + e.putString("user", login); + } + e.putString("password", DedalHelper.encodeB64(password.getText().toString())); +// e.putInt("refresh", refresh.getSelectedItemPosition()); + String dirPath = Environment.getExternalStorageDirectory()+ "/dedal/"+ login; + e.putString("dir", dirPath); + e.putBoolean("tablet", true); + e.putInt("refresh", 2); + + e.commit(); + + // Utwórz folder użytkownika jeśli nie istnieje + try { + File dir = new File(dirPath); + if (!dir.exists()) { + boolean ok = dir.mkdirs(); + if (!ok) { + Toast.makeText(this, "Nie można utworzyć katalogu:" + dirPath, Toast.LENGTH_LONG).show(); + } + } + } catch (Throwable t) { + Log.e(LOG, "Błąd tworzenia katalogu: " + t.getMessage(), t); + } + + //usunięcie starej aplikacji: + deleteFiles(Environment.getExternalStorageDirectory()+ "/likesoft"); + deleteFiles(Environment.getExternalStorageDirectory()+ "/likesofttest"); + + File fLockLogin = new File(prefs.getString("dir", "") + "/dedalsrv.wrongLogin"); + if( fLockLogin.exists()){ + fLockLogin.delete(); + } + + } + private void updateUI() { +// tablet.setChecked(prefs.getBoolean("tablet", false)); +// hostName.setText(prefs.getString("hostName", "http://likesoft/dedal/develop/psql")); +// hostName.setText(prefs.getString("hostName", "https://dedal.eos-ksi.pl")); + user.setText(prefs.getString("user", "")); + password.setText(""); + textViewHostUrl.setText(prefs.getString("hostName", "https://dedal.eos-ksi.pl")); + + //password.setText(prefs.getString("password", "")); +// refresh.setSelection(prefs.getInt("refresh", 0)); + + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.prefer, menu); + return true; + } + +} diff --git a/app/src/main/java/com/likesoft/mdedal/RefreshLayoutAndThread.java b/app/src/main/java/com/likesoft/mdedal/RefreshLayoutAndThread.java new file mode 100644 index 0000000..aaa3477 --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/RefreshLayoutAndThread.java @@ -0,0 +1,294 @@ +package com.likesoft.mdedal; + +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Color; +import android.os.AsyncTask; +import android.preference.PreferenceManager; +import android.view.View; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.TextView; + + +import java.io.File; +import java.io.FileInputStream; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +/** + * Created by Kamil on 2016-02-04. + */ +abstract class RefreshLayoutAndThread extends Thread implements Runnable { + + private final static int THREAD_PERIOD = 1000; + public boolean pauseThread = false; + + Context context; + SharedPreferences prefs; + LinearLayout refreshLayout; + + //// + long lastProfileMod = 0; + TextView textDataMod; + TextView textUpload = null; + ProgressBar progress; + String sLastInfo = ""; + boolean stare = false; + + public RefreshLayoutAndThread(Context context) { + this.context = context; + prefs = PreferenceManager.getDefaultSharedPreferences(context); + + textUpload = new TextView(context); + textUpload.setPadding(20, 0, 20, 0); + } + + //protected abstract void reloadContent(); + protected abstract void whenThreadNeedToReaoad(); + protected abstract void setLastGPSInfo_abstr(); + protected void onServiceFinisz() { + + } + + public LinearLayout getRefreshLayout() { + refreshLayout = new LinearLayout(context); + + //LinearLayout refreshLayout = new LinearLayout(this); + //filterL.addView(refreshLayout); + + + + textDataMod = new TextView(context); + // = tw; + textDataMod.setTextAppearance(context, R.style.OpisTextLista); + refreshLayout.addView(textDataMod); + + progress = new ProgressBar(context); + progress.setProgress(50); + refreshLayout.addView(progress); + + + AsyncTask at = new AsyncTask() { + @Override + protected Object doInBackground(Object[] objects) { + File dLista = new File(prefs.getString("dir", "") + "/baza/lista.profil"); + if( dLista.isFile()){ + long lastMod = dLista.lastModified(); + lastProfileMod = lastMod; + setLastInfo(lastProfileMod); + } + return null; + } + }; + at.execute(); + + Button b = new Button(context); + b.setText("Odśwież"); + b.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + pauseThread = false; + //Context context = getApplicationContext(); + + Alarm alarm = new Alarm(); + alarm.CancelAlarm(context); + alarm.SetAlarm(context); + + Intent service = new Intent(context, DedalService.class); + context.startService(service); + + //todo: temp commented + //search = ""; + + //wyswietlListe(); + } + }); + + refreshLayout.addView(b); //refresh button + + return refreshLayout; + } + + public TextView getTextUpload () { + return textUpload; + } + + @Override + public void run() { + // TODO Auto-generated method stub + while( true){ + try { + Thread.sleep(THREAD_PERIOD); + if( pauseThread ) { + //Log.d("RefreshLayoutAndThread", "pause"); + } + else { + //Log.d("RefreshLayoutAndThread", "thread working"); + setLastGPSInfo_abstr(); + setLastUpdateInfo(); + setLastInfo(lastProfileMod); + + File dLista = new File(prefs.getString("dir", "") + "/baza/lista.profil"); + if (dLista.isFile()) { + long lastMod = dLista.lastModified(); + if (lastProfileMod != lastMod) { + lastProfileMod = lastMod; +// setLastInfo(lastProfileMod); +// + + textDataMod.post(new Runnable() { + @Override + public void run() { + + whenThreadNeedToReaoad(); +// ListActivity.this.recreate(); + //ListActivity.this.finish(); + } + }); + + } + } + } + } catch (InterruptedException e) { + Log.d("RefreshLayoutAndThread", "interrupted"); + break; + } + + } + + } + + private void setLastInfo(long lastProfileMod){ + //gps.isGPSEnabled + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date d = new Date(lastProfileMod); + Date dCurrent = new Date(); + long c = dCurrent.getTime() - 60*60*1000; //godzina + //Date dCurrent = new Date(); + // boolean stare = false; + + if( lastProfileMod < c){ + // dawno nie było aktualizacji + stare = true; + }else{ + stare = false; + } + + File dQ = new File(prefs.getString("dir", "") + "/queue"); + if( dQ.isDirectory() && dQ.list().length>0 ){ + //sAktualizacja = "Trwa pobieranie zleceń ("+dQ.list().length+")..."; + sLastInfo = "Trwa pobieranie zleceń ("+dQ.list().length+")... \nPoprzednia:" + + sdf.format(d); + } + else { + //sAktualizacja = ""; + sLastInfo = "Ostatnia aktualizacja:\n"; + sLastInfo += sdf.format(d); + // sLastInfo += "\n" + sdf.format(c) + " stare: " + stare; + } + + //sLastInfo = "Ostatnia akutalizacja:\n" + sdf.format(d); + + textDataMod.post(new Runnable() { + @Override + public void run() { + textDataMod.setText(sLastInfo); + + if(stare) { + textDataMod.setBackgroundColor(Color.RED); + }else{ + + textDataMod.setBackgroundColor(Color.TRANSPARENT); + //textDataMod.setTextAppearance(context, R.style.OpisTextLista); + //textDataMod.setTextAppearance(); + } + } + }); + + } + + + private int licznikUpdates=0; + private String sAktualizacja = ""; + + public void setLastUpdateInfo(){ + File fLockEnd = new File(prefs.getString("dir", "") + "/dedalsrv.lock"); + if( fLockEnd.exists()){ + + //sAktualizacja = "Aktualizacja\n zleceń ";// + kreciolek[licznikUpdates % 4]; + //licznikUpdates++; + licznikUpdates=1; + }else{ + licznikUpdates = 0; + +// File d = new File(prefs.getString("dir", "") + "/queue"); +// if( d.isDirectory() && d.list().length>0 ){ +// sAktualizacja = "Trwa pobieranie zleceń ("+d.list().length+")..."; +// } +// else { +// sAktualizacja = ""; +// } + } + sAktualizacja = ""; + + File fconn = new File(prefs.getString("dir", "") + "/dedalsrv.connection"); + if( fconn.exists()){ + sAktualizacja = "!";//Problem z połączeniem! VPN lub błędne hasło."; + } + File fLockCon = new File(prefs.getString("dir", "") + "/dedalsrv.connection_password"); + if( fLockCon.exists()){ + sAktualizacja = "Zmien hasło, zlecenie NIE zapisane!"; + } + + File fConnectionStatus = new File(prefs.getString("dir", "") + "/dedal.status"); + if( fConnectionStatus.exists()){ + String msg = ""; + try { + FileInputStream fin = new FileInputStream(fConnectionStatus); + msg = ListActivity.readFile(fin); + }catch (Exception e){ + Log.e("ListActivity", e.getMessage(), e); + + } + sAktualizacja += msg; + } + + + File fLockLogin = new File(prefs.getString("dir", "") + "/dedalsrv.wrongLogin"); + if( fLockLogin.exists()){ + sAktualizacja = "Ustaw login i hasło. "; + if(fLockLogin.exists()){ + if( context instanceof ListActivity) { + ListActivity lA = (ListActivity)context; + fLockLogin.delete(); + Intent i = new Intent(lA, lA.getPreferActivity()); + lA.startActivityForResult(i, lA.SHOW_PREFERENCES); + } + } + } + + textUpload.post(new Runnable() { + @Override + public void run() { + textUpload.setText(sAktualizacja); + if( "".equals(sAktualizacja)){ + textUpload.setBackgroundColor(Color.parseColor("white")); + }else{ + textUpload.setBackgroundColor(Color.parseColor("yellow")); + } + if( licznikUpdates==0){ + if( progress.getVisibility() == View.VISIBLE ) { + onServiceFinisz(); + } + progress.setVisibility(View.INVISIBLE); + }else{ + progress.setVisibility(View.VISIBLE); + } + } + }); + } +} diff --git a/app/src/main/java/com/likesoft/mdedal/TableHeadersActivity.java b/app/src/main/java/com/likesoft/mdedal/TableHeadersActivity.java new file mode 100644 index 0000000..a70ca04 --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/TableHeadersActivity.java @@ -0,0 +1,817 @@ +package com.likesoft.mdedal; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.util.Date; +import java.util.Iterator; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import com.likesoft.mdedal.gui.BorderTextView; +import com.likesoft.mdedal.gui.MTextView; +//import com.likesoft.mdedaltest.*; +import com.likesoft.mdedaldemo.*; + +import android.app.Activity; +import android.content.ClipData; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Color; +import android.graphics.Point; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.view.Display; +//import android.util.Log; +import android.view.DragEvent; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.DragShadowBuilder; +import android.view.View.OnClickListener; +import android.view.View.OnDragListener; +import android.view.View.OnTouchListener; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.EditText; +import android.widget.GridView; +import android.widget.HorizontalScrollView; +import android.widget.LinearLayout; +import android.widget.RelativeLayout; +import android.widget.ScrollView; +import android.widget.TextView; + +public class TableHeadersActivity extends Activity { + + String id_profilu = null; + String nazwa_profilu = null; + LinearLayout lContent = null; + LinearLayout lContent_nieuzyte = null; + JSONArray jkolumny_all = null; + SharedPreferences prefs; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + Context context = getApplicationContext(); + prefs = PreferenceManager.getDefaultSharedPreferences(context); + Log.setFileName(prefs.getString("dir", "")); + Log.setEH(); + + Bundle extras = getIntent().getExtras(); + if (extras != null) { + id_profilu = extras.getString("id_profilu"); + } + + File dtemp1 = new File(prefs.getString("dir", "") + "/temp/widok_profil_temp_"+id_profilu+".json"); + dtemp1.delete(); + + loadjKolumny_all(); + + HorizontalScrollView lMainScroll = new HorizontalScrollView(this); + LinearLayout lMain = new LinearLayout(this); + + ScrollView vertScroll = new ScrollView(this); + lMainScroll.addView(vertScroll); + + vertScroll.addView(lMain); + lMain.setOrientation(LinearLayout.VERTICAL); + lMain.setOnDragListener(new MyDragListenerBack()); + + LinearLayout lHeader = new LinearLayout(this); + lHeader.setOrientation(LinearLayout.VERTICAL); + lMain.addView(lHeader); + + lContent = new LinearLayout(this); + LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); + + layoutParams.setMargins(0, 0, 0, 30); + lContent.setLayoutParams(layoutParams); + + Display display = getWindowManager().getDefaultDisplay(); + Point size = new Point(); + display.getSize(size); + int width = size.x; + + lContent.setMinimumWidth(width); + lMain.addView(lContent); + // lContent.setMinimumHeight(30); + lContent.setBackgroundColor(Color.YELLOW); + lContent.setOnDragListener(new MyDragListener_move_end(Color.CYAN, Color.YELLOW)); + + //lContent.setLayoutParams(new LinearLayout.LayoutParams(300,600)); + + lContent_nieuzyte = new LinearLayout(this); + lMain.addView(lContent_nieuzyte); + lContent_nieuzyte.setMinimumHeight(55); + lContent_nieuzyte.setBackgroundColor(Color.DKGRAY); + lContent_nieuzyte.setOnDragListener(new MyDragListener_nieuzyte(Color.CYAN, Color.DKGRAY)); + lContent_nieuzyte.setLayoutParams(layoutParams); + + TextView tw = new TextView(this); + lHeader.addView(tw); + if( id_profilu == null ) { + + tw.setText("Nie wykryto id_profilu !"); + Log.d("my_debug", "nie wykryto profilu"); + setContentView(lMainScroll); + //setContentView(lMain); + return ; + } + + //EditText et = new EditText(this); + tw.setTextSize(20); + tw.setPadding(5,5,5,5); + tw.setText("Profil: "+nazwa_profilu); + + TextView tw_opis = new TextView(this); + lHeader.addView(tw_opis); + tw_opis.setPadding(5,5,5,15); + tw_opis.setText("Poniżej wyświetlona jest lista nagłówków z tabeli listy zleceń. Poniższy układ jest wczytywany dla profilu: "+nazwa_profilu+".\n" + + "Aby zmienić układ, naciśnij wybrany element, przytrzymaj a następnie przesuń w wybrane miejsce. \n" + + "Aby dany element nie był wyświetlany w tabeli zleceń, przesuń go na dolny szary pasek. \n" + + "Po zakończeniu ustawiania nagłówków, kliknij 'Zapisz układ'. Wtedy nastąpi wysłanie układu na serwer. \n" + + "Zostaniesz przekierowany na listę zleceń i należy poczekać aż lista przeładuje się z nowym układem.\n" + + "UWAGA: Zmiana nagłówków działa tylko w trybie online (wymaga aktywnego połączenia internetowego).\n" + + "Przycisk: 'Przywróć ustawienia domyślne' - skasuje ustawienia nagłówków i przywróci domyślny układ. \n" + + "\tPo naciśnięciu aplikacja przejdzie do listy zleceń. Należy poczekać aż system skomunikuje się z serwerem i przeładuję liste.\n" + + "Przycisk 'Cofnij zmiany' - skasuje aktualne ustawienie\n" + + "Przycisk 'Wyjdź' - skasuje aktualne ustawienie i wyjdzie do listy zleceń"); + + + ////////// + + drawContent(); + + LinearLayout footer = new LinearLayout(this); + footer.setOrientation(LinearLayout.HORIZONTAL); + lMain.addView(footer); + + Button zapisz = new Button(this); + zapisz.setText("Zapisz układ"); + zapisz.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + Date d = new Date(); + String genName = "widok_profil_"+d.getTime() + ".mod"; + File dstDir = new File(prefs.getString("dir", "") + "/upload_widok_profil_mod"); + if( !dstDir.isDirectory()){ dstDir.mkdirs(); } + File fMod = new File(prefs.getString("dir", "") + "/upload_widok_profil_mod/" + genName); + + File dtemp = new File(prefs.getString("dir", "") + "/temp/widok_profil_temp_"+id_profilu+".json"); + if ( dtemp.exists() ) { + JSONObject jFile; + try { + String s = DedalHelper.getFileContent(dtemp.getAbsolutePath()); + jFile = new JSONObject(s); + jFile.put("id_profilu", id_profilu); + DedalHelper.putFileContent(dtemp.getAbsolutePath(), jFile.toString()); + } catch (JSONException e) { + Log.e("TableHeadersActivity", "", e); + } + } + + // wystartuj/obudz serwis + Context context = getApplicationContext(); + Intent service = new Intent(context, DedalService.class); + context.startService(service); + + finish(); + + } + }); + footer.addView(zapisz); + + Button przywroc = new Button(this); + przywroc.setText("Przywróć domyślny układ nagłówków"); + przywroc.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + try { + File dtemp1 = new File(prefs.getString("dir", "") + "/temp/widok_profil_temp_"+id_profilu+".json"); + dtemp1.delete(); + + JSONObject jF = new JSONObject(); + jF.put("id_profilu", id_profilu); + jF.put("reset", "true"); + + Date d = new Date(); + String genName = "widok_profil_"+d.getTime() + ".mod"; + DedalHelper.putFileContent(prefs.getString("dir", "") + "/upload_widok_profil_mod/" + genName, jF.toString()); + } catch (JSONException e) { + //e.printStackTrace(); + Log.e("TableHeadersActivity", "", e); + } + + // wystartuj/obudz serwis + Context context = getApplicationContext(); + Intent service = new Intent(context, DedalService.class); + context.startService(service); + + finish(); + } + }); + footer.addView(przywroc); + + Button clear = new Button(this); + clear.setText("Cofnij zmiany"); + clear.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + File dtemp1 = new File(prefs.getString("dir", "") + "/temp/widok_profil_temp_"+id_profilu+".json"); + dtemp1.delete(); + + TableHeadersActivity.this.recreate(); + } + }); + footer.addView(clear); + + Button wyjdz = new Button(this); + wyjdz.setText("Wyjdź"); + wyjdz.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + File dtemp1 = new File(prefs.getString("dir", "") + "/temp/widok_profil_temp_"+id_profilu+".json"); + dtemp1.delete(); + //TableHeadersActivity.this.recreate(); + finish(); + //drawContent(); + } + }); + footer.addView(wyjdz); + + setContentView(lMainScroll); + + this.setTitle("Zarządzanie nagłówkami tabeli"); + } + + private void loadjKolumny_all() { + BufferedReader buf; + File dLista = new File(prefs.getString("dir", "") + "/baza/lista.profil"); + + + JSONObject jFile; + try { + + String sJson = DedalHelper.getFileContent(dLista.getAbsolutePath()); + jFile = new JSONObject(sJson); + + JSONObject jProfiles = jFile.getJSONObject("profile"); + JSONObject jProfil = jProfiles.getJSONObject(id_profilu); + nazwa_profilu = jProfil.getString("nazwa_profilu"); + JSONArray jKolumny_uzyte = jProfil.getJSONArray("profil_kolumny"); + //if( jProfil.has("kolumny_nieuzyte") && !jProfil.getString("kolumny_nieuzyte").equals("null") && jProfil.getJSONArray("kolumny_nieuzyte") != null ) { + JSONArray jKolumny_nieuzyte = jProfil.getJSONArray("kolumny_nieuzyte"); + jkolumny_all = new JSONArray(jKolumny_uzyte.toString()); + if( jKolumny_nieuzyte != null && jKolumny_nieuzyte.length() > 0 ) { + for( int i = 0 ; i < jKolumny_nieuzyte.length() ; i++ ) { + jkolumny_all.put( jKolumny_nieuzyte.getJSONObject(i) ); + } + } + //} + //Log.d("my_debug", "jkolumny_all: "+jkolumny_all.toString()); + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + Log.e("DEDAL", "blad parsowania lista.profil", e); + } + + + + } + + private void drawContent() { + try { + //lContent = null; + lContent.removeAllViews(); + BufferedReader buf; + JSONArray jKolumny = null; + File dtemp = new File(prefs.getString("dir", "") + "/temp/widok_profil_temp_"+id_profilu+".json"); + if ( dtemp.exists() ) { + String sJson = DedalHelper.getFileContent(dtemp.getAbsolutePath()); + JSONObject jFile = new JSONObject(sJson); + jKolumny = jFile.getJSONArray("profil_kolumny"); + Log.d("my_debug", "1: "+jKolumny.toString()); + } + else { + File dLista = new File(prefs.getString("dir", "") + "/baza/lista.profil"); + String sJson = DedalHelper.getFileContent(dLista.getAbsolutePath()); + + JSONObject jFile = new JSONObject(sJson); + + JSONObject jProfiles = jFile.getJSONObject("profile"); + JSONObject jProfil = jProfiles.getJSONObject(id_profilu); + jKolumny = jProfil.getJSONArray("profil_kolumny"); + + } + int k = 0; + for( k = 0; k < jKolumny.length(); k++) + { + BorderTextView mtw = new BorderTextView(this); + +// RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); +// params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); +// mtw.setLayoutParams(params); + + mtw.setTextAppearance(this, R.style.OpisText); + mtw.setPadding(15, 15, 15, 15); + String kod = jKolumny.getJSONObject(k).getString("kod"); + mtw.setCode(kod); + mtw.setId(k); + String nazwa = jKolumny.getJSONObject(k).getString("nazwa"); + mtw.setText(nazwa); + //tw.setBackgroundColor(Color.parseColor("#AFA5F0"));// #FAFAD2 + //mtw.setPadding(5, 3, 5, 2); +// tw.setTextSize(TypedValue.COMPLEX_UNIT_MM, 5); + mtw.setBackgroundColor(Color.GREEN); + + mtw.setOnTouchListener(new MyTouchListener()); + mtw.setOnDragListener(new MyDragListener(Color.CYAN, Color.GREEN)); + + lContent.addView(mtw); + } + TextView tw_end = new TextView(this); + tw_end.setPadding(0, 18, 0, 18); + tw_end.setText(" "); + tw_end.setWidth(150); + lContent.addView(tw_end); + + lContent_nieuzyte.removeAllViews(); + Log.d("my_debug", "Ajkolumny_all: "+jkolumny_all.toString()); + boolean cont = false; + for( int m=0; m < jkolumny_all.length(); m++) + { + cont = false; + // sprawdz czy jest używany + for( int l=0; l< jKolumny.length(); l++) + { + //Log.d("my_debug", "uzyty: "+jKolumny.getJSONObject(l).getString("kod")+", all: "+jkolumny_all.getJSONObject(k).getString("kod")); + if( jKolumny.getJSONObject(l).getString("kod").equals(jkolumny_all.getJSONObject(m).getString("kod")) ) { + cont = true; + break; + } + } + if( cont ) { + continue; + } + + BorderTextView mtw = new BorderTextView(this); + mtw.setTextAppearance(this, R.style.OpisText); + mtw.setPadding(15, 15, 15, 15); + String kod = jkolumny_all.getJSONObject(m).getString("kod"); + mtw.setCode(kod); + k++; + mtw.setId(k); + String nazwa = jkolumny_all.getJSONObject(m).getString("nazwa"); + mtw.setText(nazwa); + mtw.setBackgroundColor(Color.RED); + + mtw.setOnTouchListener(new MyTouchListener()); + //mtw.setOnDragListener(new MyDragListener()); + lContent_nieuzyte.addView(mtw); + } + + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + class MyDragListenerBack implements OnDragListener { + + @Override + public boolean onDrag(View onDropEl, DragEvent event) { + int action = event.getAction(); + View movingEl = (View) event.getLocalState(); + switch (event.getAction()) { + case DragEvent.ACTION_DRAG_STARTED: + // do nothing + break; + case DragEvent.ACTION_DRAG_ENTERED: + //v.setBackgroundDrawable(enterShape); + //onDropEl.setBackgroundColor(Color.GRAY); + break; + case DragEvent.ACTION_DRAG_EXITED: + //v.setBackgroundDrawable(normalShape); + //onDropEl.setBackgroundColor(Color.RED); + break; + case DragEvent.ACTION_DROP: + // Dropped, reassign View to ViewGroup + movingEl.setVisibility(View.VISIBLE); + movingEl.setAlpha(1); + break; + case DragEvent.ACTION_DRAG_ENDED: + //v.setBackgroundDrawable(normalShape); + default: + break; + } + return true; + } + + } + + class MyDragListener implements OnDragListener { + + int color_entered = 0; + int color_exited = 0; + + public MyDragListener(int color_entered, int color_exited) { + this.color_entered = color_entered; + this.color_exited = color_exited; + } + + @Override + public boolean onDrag(View onDropEl, DragEvent event) { + int action = event.getAction(); + View movingEl = (View) event.getLocalState(); + + int id_moving = movingEl.getId(); + int id_drop = onDropEl.getId(); + + + + int side = Math.round(event.getX() - onDropEl.getMeasuredWidth() / 2 ); // side < 0 uposzczone po lewej stronie elementu, side > 0 upuszczone po prawej stronie + switch (event.getAction()) { + case DragEvent.ACTION_DRAG_STARTED: + // do nothing + break; + case DragEvent.ACTION_DRAG_ENTERED: + //v.setBackgroundDrawable(enterShape); + + onDropEl.setBackgroundColor(color_entered); + break; + case DragEvent.ACTION_DRAG_EXITED: + //v.setBackgroundDrawable(normalShape); + onDropEl.setBackgroundColor(color_exited); + break; + case DragEvent.ACTION_DROP: + // Dropped, reassign View to ViewGroup + + if( id_moving == id_drop ) { + movingEl.setAlpha(1); + movingEl.setBackgroundColor(color_exited); + break; + } + + JSONObject jmain = new JSONObject(); + JSONArray jprofil = new JSONArray(); + // create Json + +// float x = event.getX(); +// float y = event.getY(); + + + Log.d("my_debug", "side: "+side); + + + try { + for (int i = 0 ; i < 200 ; i++ ) { + MTextView v = (MTextView)TableHeadersActivity.this.findViewById(i); + if ( v == null) { + break; + } + if( i == id_drop || i == id_moving) { + //if( id_drop < id_moving ) { + if( i == id_drop ) { + //i = id_moving; + MTextView v_temp = null; + JSONObject jcurr = null; + if(side >= 0 ) { + + v_temp = (MTextView)TableHeadersActivity.this.findViewById(id_drop); + jcurr = new JSONObject(); + jcurr.put("kod", v_temp.getCode()); + jcurr.put("nazwa", v_temp.getText()); + jprofil.put(jcurr); + + v_temp = (MTextView)TableHeadersActivity.this.findViewById(id_moving); + if( v_temp != null ) { + jcurr = new JSONObject(); + jcurr.put("kod", v_temp.getCode()); + jcurr.put("nazwa", v_temp.getText()); + jprofil.put(jcurr); + } + } + else { + v_temp = (MTextView)TableHeadersActivity.this.findViewById(id_moving); + if( v_temp != null ) { + jcurr = new JSONObject(); + jcurr.put("kod", v_temp.getCode()); + jcurr.put("nazwa", v_temp.getText()); + jprofil.put(jcurr); + } + + v_temp = (MTextView)TableHeadersActivity.this.findViewById(id_drop); + jcurr = new JSONObject(); + jcurr.put("kod", v_temp.getCode()); + jcurr.put("nazwa", v_temp.getText()); + jprofil.put(jcurr); + } + } + if( i == id_moving ) { + continue; + } + } + else { + JSONObject jcurr = new JSONObject(); + + jcurr.put("kod", v.getCode()); + jcurr.put("nazwa", v.getText()); + jprofil.put(jcurr); + } + } + + jmain.put("profil_kolumny", jprofil); + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + onDropEl.setBackgroundColor(Color.DKGRAY); + movingEl.setVisibility(View.VISIBLE); + + String genName = "widok_profil_temp_"+id_profilu+".json"; + File dstDir = new File(prefs.getString("dir", "") + "/temp"); + if( !dstDir.isDirectory()){ dstDir.mkdirs(); } + File fMod = new File(prefs.getString("dir", "") + "/temp/" + genName); + FileOutputStream fos; + try { + fos = new FileOutputStream(fMod); + fos.write(jmain.toString().getBytes()); + fos.flush(); + fos.close(); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + //TableHeadersActivity.this.recreate(); + drawContent(); + + break; + case DragEvent.ACTION_DRAG_ENDED: + //v.setBackgroundDrawable(normalShape); + default: + break; + } + return true; + } + + } + + class MyDragListener_move_end implements OnDragListener { + + //nieużywane + int color_entered = 0; + int color_exited = 0; + + public MyDragListener_move_end(int color_entered, int color_exited) { + this.color_entered = color_entered; + this.color_exited = color_exited; + } + + @Override + public boolean onDrag(View onDropEl, DragEvent event) { + int action = event.getAction(); + View movingEl = (View) event.getLocalState(); + + //int side = Math.round(event.getX() - onDropEl.getMeasuredWidth() / 2 ); // side < 0 uposzczone po lewej stronie elementu, side > 0 upuszczone po prawej stronie + switch (event.getAction()) { + case DragEvent.ACTION_DRAG_STARTED: + // do nothing + break; + case DragEvent.ACTION_DRAG_ENTERED: + //v.setBackgroundDrawable(enterShape); + //onDropEl.setBackgroundColor(color_entered); + break; + case DragEvent.ACTION_DRAG_EXITED: + //v.setBackgroundDrawable(normalShape); + //onDropEl.setBackgroundColor(color_exited); + break; + case DragEvent.ACTION_DROP: + // Dropped, reassign View to ViewGroup + + int id_moving = movingEl.getId(); + int id_drop = onDropEl.getId(); + + JSONObject jmain = new JSONObject(); + JSONArray jprofil = new JSONArray(); + // create Json + +// float x = event.getX(); +// float y = event.getY(); + + + //Log.d("my_debug", "side: "+side); + + + try { + for (int i = 0 ; i < 200 ; i++ ) { + MTextView v = (MTextView)TableHeadersActivity.this.findViewById(i); + if ( v == null) { + break; + } + + if( i == id_moving ) { + continue; + } + else { + JSONObject jcurr = new JSONObject(); + + jcurr.put("kod", v.getCode()); + jcurr.put("nazwa", v.getText()); + jprofil.put(jcurr); + } + } + MTextView v_temp = null; + JSONObject jcurr = null; + v_temp = (MTextView)TableHeadersActivity.this.findViewById(id_moving); + if( v_temp != null ) { + jcurr = new JSONObject(); + jcurr.put("kod", v_temp.getCode()); + jcurr.put("nazwa", v_temp.getText()); + jprofil.put(jcurr); + } + + jmain.put("profil_kolumny", jprofil); + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + onDropEl.setBackgroundColor(Color.YELLOW); + movingEl.setVisibility(View.VISIBLE); + + String genName = "widok_profil_temp_"+id_profilu+".json"; + File dstDir = new File(prefs.getString("dir", "") + "/temp"); + if( !dstDir.isDirectory()){ dstDir.mkdirs(); } + File fMod = new File(prefs.getString("dir", "") + "/temp/" + genName); + FileOutputStream fos; + try { + fos = new FileOutputStream(fMod); + fos.write(jmain.toString().getBytes()); + fos.flush(); + fos.close(); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + //TableHeadersActivity.this.recreate(); + drawContent(); + + break; + case DragEvent.ACTION_DRAG_ENDED: + //v.setBackgroundDrawable(normalShape); + default: + break; + } + return true; + } + + } + + class MyDragListener_nieuzyte implements OnDragListener { + + int color_entered = 0; + int color_exited = 0; + + public MyDragListener_nieuzyte(int color_entered, int color_exited) { + this.color_entered = color_entered; + this.color_exited = color_exited; + } + + @Override + public boolean onDrag(View onDropEl, DragEvent event) { + int action = event.getAction(); + View movingEl = (View) event.getLocalState(); + switch (event.getAction()) { + case DragEvent.ACTION_DRAG_STARTED: + // do nothing + break; + case DragEvent.ACTION_DRAG_ENTERED: + //v.setBackgroundDrawable(enterShape); + onDropEl.setBackgroundColor(color_entered); + break; + case DragEvent.ACTION_DRAG_EXITED: + //v.setBackgroundDrawable(normalShape); + onDropEl.setBackgroundColor(color_exited); + break; + case DragEvent.ACTION_DROP: + // Dropped, reassign View to ViewGroup + + int id_moving = movingEl.getId(); + int id_drop = onDropEl.getId(); + + JSONObject jmain = new JSONObject(); + JSONArray jprofil = new JSONArray(); + // create Json + try { + for (int i = 0 ; i < 200 ; i++ ) { + MTextView v = (MTextView)TableHeadersActivity.this.findViewById(i); + if ( v == null) { + break; + } + if( i == id_drop || i == id_moving) { + //if( id_drop < id_moving ) { + if( i == id_drop ) { + //i = id_moving; + MTextView v_temp = null; + JSONObject jcurr = null; + v_temp = (MTextView)TableHeadersActivity.this.findViewById(id_drop); + jcurr = new JSONObject(); + jcurr.put("kod", v_temp.getCode()); + jcurr.put("nazwa", v_temp.getText()); + jprofil.put(jcurr); + + v_temp = (MTextView)TableHeadersActivity.this.findViewById(id_moving); + if( v_temp != null ) { + jcurr = new JSONObject(); + jcurr.put("kod", v_temp.getCode()); + jcurr.put("nazwa", v_temp.getText()); + jprofil.put(jcurr); + } + } + if( i == id_moving ) { + continue; + } + } + else { + JSONObject jcurr = new JSONObject(); + + jcurr.put("kod", v.getCode()); + jcurr.put("nazwa", v.getText()); + jprofil.put(jcurr); + } + } + + jmain.put("profil_kolumny", jprofil); + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + onDropEl.setBackgroundColor(Color.DKGRAY); + movingEl.setVisibility(View.VISIBLE); + + String genName = "widok_profil_temp_"+id_profilu+".json"; + File dstDir = new File(prefs.getString("dir", "") + "/temp"); + if( !dstDir.isDirectory()){ dstDir.mkdirs(); } + File fMod = new File(prefs.getString("dir", "") + "/temp/" + genName); + FileOutputStream fos; + try { + fos = new FileOutputStream(fMod); + fos.write(jmain.toString().getBytes()); + fos.flush(); + fos.close(); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + //TableHeadersActivity.this.recreate(); + drawContent(); + + break; + case DragEvent.ACTION_DRAG_ENDED: + //v.setBackgroundDrawable(normalShape); + default: + break; + } + return true; + } + + } + + private final class MyTouchListener implements OnTouchListener { + + @Override + public boolean onTouch(View view, MotionEvent motionEvent) { + if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { + ClipData data = ClipData.newPlainText("", ""); + DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view); + view.startDrag(data, shadowBuilder, view, 0); + //int alpha = 0; + //((TextView) view).setTextColor(Color.argb(alpha, 255, 0, 0)); + view.setAlpha((float)0.3); + //view.setBackgroundColor(Color.YELLOW); + //view.setVisibility(View.INVISIBLE); + return true; + } else { + return false; + } + } + } +} diff --git a/app/src/main/java/com/likesoft/mdedal/TimePickerFragment.java b/app/src/main/java/com/likesoft/mdedal/TimePickerFragment.java new file mode 100644 index 0000000..e585b40 --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/TimePickerFragment.java @@ -0,0 +1,99 @@ +package com.likesoft.mdedal; + +import android.app.Activity; +import android.app.Dialog; +import android.app.DialogFragment; +import android.app.TimePickerDialog; +import android.content.Intent; +import android.os.Bundle; +import android.widget.TextView; +import android.widget.TimePicker; +import android.widget.Toast; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.GregorianCalendar; + +/** + * Created by Kamil on 2016-05-12. + */ +public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener { + + public Integer nr_zlecenia; + public Activity act; + public String data_walidacja_do = null; + public TextView tv = null; + public Calendar setDate = null; + + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + // Use the current date as the default date in the picker + final Calendar c = Calendar.getInstance(); + int hour = c.get(Calendar.HOUR_OF_DAY); + int minute = c.get(Calendar.MINUTE); + //int day = c.get(Calendar.DAY_OF_MONTH); + + // Create a new instance of DatePickerDialog and return it + return new TimePickerDialog(getActivity(), this, hour, minute, true); + } + + private static final String DATA_KOD = "nast_wizyta_data"; + + @Override + public void onTimeSet(TimePicker timePicker, int i, int i2) { + setDate.add(Calendar.HOUR, i); + setDate.add(Calendar.MINUTE, i2); + +// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); +// String date_string = sdf.format(setDate.getTime()); + + + Calendar c = setDate; //new GregorianCalendar(year, month, day); + Calendar cToday = new GregorianCalendar(); + + Calendar data_walidacja_do_cal = null; + if( data_walidacja_do != null ) { + try { + data_walidacja_do_cal = Calendar.getInstance(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + data_walidacja_do_cal.setTime(sdf.parse(data_walidacja_do));// all done + } catch (ParseException e) { + e.printStackTrace(); + } + } + + + if( cToday.compareTo(c)>0){ + Toast.makeText(act.getApplicationContext(), + "Nie można wybrać daty wstecznej dla wizyty nr: " + nr_zlecenia, + Toast.LENGTH_LONG).show(); + } + else if( data_walidacja_do_cal != null && c.compareTo(data_walidacja_do_cal)>0 ) { + Toast.makeText(act.getApplicationContext(), + "Nie można wybrać daty przekraczającej datę obsługi: " + data_walidacja_do, + Toast.LENGTH_LONG).show(); + } + else { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + String cString = sdf.format(c.getTime()); + + AsyncCallChangeDate task = new AsyncCallChangeDate(act, nr_zlecenia + "", DATA_KOD, cString) { + @Override + protected void reloadContent() { + // drawContent(); + final Intent intent = new Intent(); + intent.setAction("blah"); + getActivity().sendBroadcast(intent); + dismiss(); + } + + @Override + public void loadInputs() { + // loadJsons(); + } + }; // week_day_dates[id_drop]); + task.execute(); + } + } +} diff --git a/app/src/main/java/com/likesoft/mdedal/gui/BorderLinearLayout.java b/app/src/main/java/com/likesoft/mdedal/gui/BorderLinearLayout.java new file mode 100644 index 0000000..469eef2 --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/gui/BorderLinearLayout.java @@ -0,0 +1,45 @@ +package com.likesoft.mdedal.gui; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.widget.LinearLayout; + +/** + * Created by Kamil on 2016-01-23. + */ +public class BorderLinearLayout extends LinearLayout { + + int color; + + public BorderLinearLayout(Context context) { + super(context); + this.color = Color.BLACK; + //setPadding(5, 3, 5, 3); + setWillNotDraw(false) ; + + } + public BorderLinearLayout(Context context, int color) { + super(context); + // TODO Auto-generated constructor stub + this.color = color; + //setPadding(5, 3, 5, 3); + setWillNotDraw(false) ; + } + @Override + protected void onDraw(Canvas canvas) { + // TODO Auto-generated method stub + super.onDraw(canvas); + + int bottom = getMeasuredHeight()-1; + int right = getMeasuredWidth()-1; + Paint paint = new Paint(); + paint.setColor(color); + canvas.drawLine(1, 0, 1, bottom, paint); + canvas.drawLine(0, bottom, right, bottom, paint); + canvas.drawLine(right, bottom, right, 0, paint); + canvas.drawLine(right, 0, 0, 0, paint); + //canvas.drawRect(0, 0, right, bottom, paint); + } +} diff --git a/app/src/main/java/com/likesoft/mdedal/gui/BorderTextView.java b/app/src/main/java/com/likesoft/mdedal/gui/BorderTextView.java new file mode 100644 index 0000000..3002a66 --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/gui/BorderTextView.java @@ -0,0 +1,38 @@ +package com.likesoft.mdedal.gui; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.widget.TableRow; +import android.widget.TextView; + +import com.likesoft.mdedal.R; + + +public class BorderTextView extends MTextView { + + public BorderTextView(Context context) { + super(context); + // TODO Auto-generated constructor stub + setPadding(5, 3, 5, 3); + setTextAppearance(context, R.style.OpisText); + // setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); + } + @Override + protected void onDraw(Canvas canvas) { + // TODO Auto-generated method stub + super.onDraw(canvas); + + int bottom = getMeasuredHeight()-1; + int right = getMeasuredWidth()-1; + Paint paint = new Paint(); + paint.setColor(Color.BLACK); + canvas.drawLine(1, 0, 1, bottom, paint); + canvas.drawLine(0, bottom, right, bottom, paint); + canvas.drawLine(right, bottom, right, 0, paint); + canvas.drawLine(right, 0, 0, 0, paint); + //canvas.drawRect(0, 0, right, bottom, paint); + } + +} diff --git a/app/src/main/java/com/likesoft/mdedal/gui/ButtonDate.java b/app/src/main/java/com/likesoft/mdedal/gui/ButtonDate.java new file mode 100644 index 0000000..38b8cd0 --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/gui/ButtonDate.java @@ -0,0 +1,20 @@ +package com.likesoft.mdedal.gui; + +import android.content.Context; +import android.widget.Button; +import android.widget.EditText; + +public class ButtonDate extends Button { + private int edId; + public int getEdId() { + return edId; + } + public void setEdId(int edId) { + this.edId = edId; + } + public ButtonDate(Context context) { + super(context); + // TODO Auto-generated constructor stub + } + +} diff --git a/app/src/main/java/com/likesoft/mdedal/gui/MLinearLayout.java b/app/src/main/java/com/likesoft/mdedal/gui/MLinearLayout.java new file mode 100644 index 0000000..79894b9 --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/gui/MLinearLayout.java @@ -0,0 +1,28 @@ +package com.likesoft.mdedal.gui; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.widget.LinearLayout; +import android.widget.RelativeLayout; + +public class MLinearLayout extends LinearLayout { + + @Override + protected void onDraw(Canvas canvas) { + // TODO Auto-generated method stub + super.onDraw(canvas); + + int height = getMeasuredHeight(); + Paint paint = new Paint(); + paint.setColor(Color.BLUE); + canvas.drawLine(0, 0, 0, height, paint); + } + + public MLinearLayout(Context context) { + super(context); + // TODO Auto-generated constructor stub + } + +} diff --git a/app/src/main/java/com/likesoft/mdedal/gui/MTextView.java b/app/src/main/java/com/likesoft/mdedal/gui/MTextView.java new file mode 100644 index 0000000..8988abf --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedal/gui/MTextView.java @@ -0,0 +1,25 @@ +package com.likesoft.mdedal.gui; + +import android.content.Context; +import android.view.ViewGroup; +import android.widget.TextView; + + +public class MTextView extends TextView { + private String code; + public MTextView(Context context) { + super(context); + // TODO Auto-generated constructor stub +// this.setMinWidth(60); +// this.setMinimumWidth(120); +// setLayoutParams(new ViewGroup.LayoutParams( +// ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + } + public String getCode() { + return code; + } + public void setCode(String code) { + this.code = code; + } + +} diff --git a/app/src/main/java/com/likesoft/mdedaldemo/test.java b/app/src/main/java/com/likesoft/mdedaldemo/test.java new file mode 100644 index 0000000..fbbfae8 --- /dev/null +++ b/app/src/main/java/com/likesoft/mdedaldemo/test.java @@ -0,0 +1,7 @@ +package com.likesoft.mdedaldemo; + +/** + * Created by darek on 2015-12-08. + */ +public class test { +} diff --git a/app/src/main/res/drawable-hdpi/ic_button_zen.png b/app/src/main/res/drawable-hdpi/ic_button_zen.png new file mode 100644 index 0000000..3fd5d16 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_button_zen.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_dedal.png b/app/src/main/res/drawable-hdpi/ic_dedal.png new file mode 100644 index 0000000..a6f68f0 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_dedal.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_launcher.png b/app/src/main/res/drawable-hdpi/ic_launcher.png new file mode 100644 index 0000000..36de730 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_launcher.png differ diff --git a/app/src/main/res/drawable-ldpi/logo.png b/app/src/main/res/drawable-ldpi/logo.png new file mode 100644 index 0000000..269dd15 Binary files /dev/null and b/app/src/main/res/drawable-ldpi/logo.png differ diff --git a/app/src/main/res/drawable-mdpi/ic_button_zen.png b/app/src/main/res/drawable-mdpi/ic_button_zen.png new file mode 100644 index 0000000..ac95d25 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/ic_button_zen.png differ diff --git a/app/src/main/res/drawable-mdpi/ic_dedal.png b/app/src/main/res/drawable-mdpi/ic_dedal.png new file mode 100644 index 0000000..9ce6b56 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/ic_dedal.png differ diff --git a/app/src/main/res/drawable-mdpi/ic_launcher.png b/app/src/main/res/drawable-mdpi/ic_launcher.png new file mode 100644 index 0000000..ca4fb79 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/ic_launcher.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_button_zen.png b/app/src/main/res/drawable-xhdpi/ic_button_zen.png new file mode 100644 index 0000000..3c07ef4 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_button_zen.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_dedal.png b/app/src/main/res/drawable-xhdpi/ic_dedal.png new file mode 100644 index 0000000..c72a5d3 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_dedal.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_launcher.png b/app/src/main/res/drawable-xhdpi/ic_launcher.png new file mode 100644 index 0000000..316051e Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_launcher.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_button_zen.png b/app/src/main/res/drawable-xxhdpi/ic_button_zen.png new file mode 100644 index 0000000..d786c58 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_button_zen.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_dedal.png b/app/src/main/res/drawable-xxhdpi/ic_dedal.png new file mode 100644 index 0000000..21189a9 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_dedal.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_launcher.png b/app/src/main/res/drawable-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..e80eb0d Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/layout/activity_calendar.xml b/app/src/main/res/layout/activity_calendar.xml new file mode 100644 index 0000000..0cd59fb --- /dev/null +++ b/app/src/main/res/layout/activity_calendar.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/app/src/main/res/layout/activity_list.xml b/app/src/main/res/layout/activity_list.xml new file mode 100644 index 0000000..ca7d34e --- /dev/null +++ b/app/src/main/res/layout/activity_list.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..0e0a051 --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_prefer.xml b/app/src/main/res/layout/activity_prefer.xml new file mode 100644 index 0000000..dc93dcc --- /dev/null +++ b/app/src/main/res/layout/activity_prefer.xml @@ -0,0 +1,112 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +