Bimba.git

ref: 85f4ee806ced6e075630cfb0cb52cead4c4a0f25

app/src/main/java/ml/adamsprogs/bimba/activities/DashActivity.kt


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package ml.adamsprogs.bimba.activities

import android.content.*
import android.os.*
import android.support.design.widget.Snackbar
import android.support.v7.app.*
import android.text.Html
import com.arlib.floatingsearchview.FloatingSearchView
import com.arlib.floatingsearchview.suggestions.model.SearchSuggestion
import ml.adamsprogs.bimba.models.*
import kotlin.concurrent.thread
import android.app.Activity
import android.support.design.widget.NavigationView
import android.support.v4.widget.*
import android.support.v7.widget.*
import android.util.Log
import android.view.*
import android.view.inputmethod.InputMethodManager
import ml.adamsprogs.bimba.*
import java.util.*

class DashActivity : AppCompatActivity(), MessageReceiver.OnTimetableDownloadListener,
        FavouritesAdapter.OnMenuItemClickListener {

    val context: Context = this
    val receiver = MessageReceiver()
    lateinit var timetable: Timetable
    var stops: ArrayList<StopSuggestion>? = null
    lateinit var drawerLayout: DrawerLayout
    lateinit var drawer: NavigationView
    lateinit var favouritesList: RecyclerView
    lateinit var searchView: FloatingSearchView
    lateinit var favourites: FavouriteStorage
    var timer = Timer()
    private lateinit var timerTask: TimerTask

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_dash)
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO)
        val toolbar = findViewById(R.id.toolbar) as Toolbar
        setSupportActionBar(toolbar)
        supportActionBar?.title = getString(R.string.merge_favourites)

        createTimerTask()

        prepareOnDownloadListener()
        startDownloaderService()

        getStops()

        prepareFavourites()

        scheduleRefresh()

        drawerLayout = findViewById(R.id.drawer_layout) as DrawerLayout
        drawer = findViewById(R.id.drawer) as NavigationView
        //drawer.setCheckedItem(R.id.drawer_home)
        drawer.setNavigationItemSelectedListener { item ->
            when (item.itemId) {
                R.id.drawer_refresh -> {
                    startDownloaderService()
                }
                R.id.drawer_help -> {
                    startActivity(Intent(context, HelpActivity::class.java))
                }
                else -> {
                }
            }
            drawerLayout.closeDrawer(drawer)
            super.onOptionsItemSelected(item)
        }

        searchView = findViewById(R.id.search_view) as FloatingSearchView

        searchView.setOnFocusChangeListener(object : FloatingSearchView.OnFocusChangeListener {
            override fun onFocus() {
                favouritesList.visibility = View.GONE
                thread {
                    val newStops = stops!!.filter { deAccent(it.body.split("\n")[0]).contains(deAccent(searchView.query), true) }
                    runOnUiThread { searchView.swapSuggestions(newStops) }
                }
            }

            override fun onFocusCleared() {
                favouritesList.visibility = View.VISIBLE
            }
        })

        searchView.setOnQueryChangeListener({ oldQuery, newQuery ->
            if (oldQuery != "" && newQuery == "")
                searchView.clearSuggestions()
            thread {
                val newStops = stops!!.filter { deAccent(it.body.split("\n")[0]).contains(deAccent(newQuery), true) }
                runOnUiThread { searchView.swapSuggestions(newStops) }
            }
        })

        searchView.setOnSearchListener(object : FloatingSearchView.OnSearchListener {
            override fun onSuggestionClicked(searchSuggestion: SearchSuggestion) {
                val imm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
                var view = (context as DashActivity).currentFocus
                if (view == null) {
                    view = View(context)
                }
                imm.hideSoftInputFromWindow(view.windowToken, 0)
                intent = Intent(context, StopActivity::class.java)
                searchSuggestion as StopSuggestion
                intent.putExtra(StopActivity.EXTRA_STOP_ID, searchSuggestion.id)
                intent.putExtra(StopActivity.EXTRA_STOP_SYMBOL, searchSuggestion.symbol)
                startActivity(intent)
            }

            override fun onSearchAction(query: String) {
            }
        })

        searchView.setOnBindSuggestionCallback { _, _, textView, item, _ ->
            val suggestion = item as StopSuggestion
            val text = suggestion.body.split("\n")
            val t = "<small><font color=\"#a0a0a0\">" + text[1] + "</font></small>"
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                textView.text = Html.fromHtml(text[0] + "<br/>" + t, Html.FROM_HTML_MODE_LEGACY)
            } else {
                @Suppress("DEPRECATION")
                textView.text = Html.fromHtml(text[0] + "<br/>" + t)
            }
        }

        searchView.attachNavigationDrawerToMenuButton(findViewById(R.id.drawer_layout) as DrawerLayout)
    }

    private fun prepareFavourites() {
        favourites = FavouriteStorage.getFavouriteStorage(context)
        val layoutManager = LinearLayoutManager(context)
        favouritesList = findViewById(R.id.favouritesList) as RecyclerView
        favouritesList.adapter = FavouritesAdapter(context, favourites.favouritesList, this)
        favouritesList.layoutManager = layoutManager
    }

    private fun scheduleRefresh() {
        timer.cancel()
        timer = Timer()
        createTimerTask()
        timer.scheduleAtFixedRate(timerTask, 0, 15000)
    }

    private fun createTimerTask() {
        timerTask = object : TimerTask() {
            override fun run() {
                for (fav in favourites) {
                    fav.registerOnVm(receiver)
                    for (t in fav.timetables) {
                        val symbol = timetable.getStopSymbol(t[Favourite.TAG_STOP]!!)
                        val line = timetable.getLineNumber(t[Favourite.TAG_LINE]!!)
                        val intent = Intent(context, VmClient::class.java)
                        intent.putExtra(VmClient.EXTRA_STOP_SYMBOL, symbol)
                        intent.putExtra(VmClient.EXTRA_LINE_NUMBER, line)
                        intent.putExtra(VmClient.EXTRA_REQUESTER,
                                "${fav.name};${t[Favourite.TAG_STOP]}${t[Favourite.TAG_LINE]}")
                        context.startService(intent)
                    }
                }

                runOnUiThread {
                    favouritesList.adapter.notifyDataSetChanged()
                }
            }
        }
    }

    private fun getStops() {
        timetable = Timetable.getTimetable(this)
        stops = timetable.getStops()
    }

    private fun prepareOnDownloadListener() {
        val filter = IntentFilter(TimetableDownloader.ACTION_DOWNLOADED)
        filter.addAction(VmClient.ACTION_DEPARTURES_CREATED)
        filter.addAction(VmClient.ACTION_NO_DEPARTURES)
        filter.addCategory(Intent.CATEGORY_DEFAULT)
        registerReceiver(receiver, filter)
        receiver.addOnTimetableDownloadListener(context as MessageReceiver.OnTimetableDownloadListener)
    }

    private fun startDownloaderService() {
        startService(Intent(context, TimetableDownloader::class.java))
    }

    override fun onBackPressed() {
        if (drawerLayout.isDrawerOpen(drawer)) {
            drawerLayout.closeDrawer(drawer)
            return
        }
        if (!searchView.setSearchFocused(false)) {
            super.onBackPressed()
        }
    }

    override fun onResume() {
        super.onResume()
        (favouritesList.adapter as FavouritesAdapter).favourites = favourites.favouritesList
        favouritesList.adapter.notifyDataSetChanged()
    }

    override fun onDestroy() {
        super.onDestroy()
        receiver.removeOnTimetableDownloadListener(context as MessageReceiver.OnTimetableDownloadListener)
        unregisterReceiver(receiver)
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_favourite_merge, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val id = item.itemId

        if (id == R.id.action_merge) {
            val names = (favouritesList.adapter as FavouritesAdapter).selectedNames
            favourites.merge(names)
            (favouritesList.adapter as FavouritesAdapter).favourites = favourites.favouritesList
            favouritesList.adapter.notifyDataSetChanged()
            (favouritesList.adapter as FavouritesAdapter).stopSelecting(names[0])
        }

        return super.onOptionsItemSelected(item)
    }

    fun deAccent(str: String): String {
        var result = str.replace('ę', 'e')
        result = result.replace('ó', 'o')
        result = result.replace('ą', 'a')
        result = result.replace('ś', 's')
        result = result.replace('ł', 'l')
        result = result.replace('ż', 'ż')
        result = result.replace('ź', 'ź')
        result = result.replace('ć', 'ć')
        result = result.replace('ń', 'n')
        return result
    }

    override fun onTimetableDownload(result: String?) {
        Log.i("Refresh", "downloaded: $result")
        val message: String
        when (result) {
            TimetableDownloader.RESULT_DOWNLOADED -> message = getString(R.string.timetable_downloaded)
            TimetableDownloader.RESULT_NO_CONNECTIVITY -> message = getString(R.string.no_connectivity)
            TimetableDownloader.RESULT_UP_TO_DATE -> message = getString(R.string.timetable_up_to_date)
            TimetableDownloader.RESULT_VALIDITY_FAILED -> message = getString(R.string.validity_failed)
            else -> message = getString(R.string.error_try_later)
        }
        timetable.refresh()
        stops = timetable.getStops()
        Snackbar.make(findViewById(R.id.drawer_layout), message, Snackbar.LENGTH_LONG).show()
    }

    override fun edit(name: String): Boolean {
        val intent = Intent(this, EditFavouriteActivity::class.java)
        intent.putExtra(EditFavouriteActivity.EXTRA_FAVOURITE, favourites.favourites[name])
        startActivity(intent)
        (favouritesList.adapter as FavouritesAdapter).favourites = favourites.favouritesList
        favouritesList.adapter.notifyDataSetChanged()
        return true
    }

    override fun delete(name: String): Boolean {
        favourites.delete(name)
        (favouritesList.adapter as FavouritesAdapter).favourites = favourites.favouritesList
        favouritesList.adapter.notifyDataSetChanged()
        return true
    }
}