Bimba.git

ref: v1.2.2

app/src/main/java/ml/adamsprogs/bimba/activities/StopActivity.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package ml.adamsprogs.bimba.activities

import java.util.*
import kotlin.collections.*

import android.content.*
import android.os.Bundle
import android.view.*
import android.support.design.widget.*
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.*
import android.support.v4.app.*
import android.support.v4.view.*
import android.support.v4.content.res.ResourcesCompat

import ml.adamsprogs.bimba.models.*
import ml.adamsprogs.bimba.*
import kotlin.concurrent.thread
import kotlinx.android.synthetic.main.activity_stop.*

class StopActivity : AppCompatActivity(), MessageReceiver.OnVmListener, Favourite.OnVmPreparedListener {
    companion object {
        val EXTRA_STOP_ID = "stopId"
        val EXTRA_STOP_SYMBOL = "stopSymbol"
        val EXTRA_FAVOURITE = "favourite"
        val REQUESTER_ID = "stopActivity"
        val SOURCE_TYPE = "sourceType"
        val SOURCE_TYPE_STOP = "stop"
        val SOURCE_TYPE_FAV = "favourite"
    }

    private var stopId: String? = null
    private var stopSymbol: String? = null
    private var favourite: Favourite? = null
    private var timetableType = "departure"
    private var sectionsPagerAdapter: SectionsPagerAdapter? = null
    private var viewPager: ViewPager? = null
    private lateinit var timetable: Timetable
    private val today = Calendar.getInstance()
    private lateinit var tabLayout: TabLayout
    private var timer = Timer()
    private lateinit var timerTask: TimerTask
    private val context = this
    private val receiver = MessageReceiver.getMessageReceiver()
    private var vmRequestId = 0

    private lateinit var sourceType: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_stop)

        timetable = Timetable.getTimetable()

        sourceType = intent.getStringExtra(SOURCE_TYPE)

        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)

        when (sourceType) {
            SOURCE_TYPE_STOP -> {
                stopId = intent.getStringExtra(EXTRA_STOP_ID)
                stopSymbol = intent.getStringExtra(EXTRA_STOP_SYMBOL)
                supportActionBar?.title = timetable.getStopName(stopId!!)
            }
            SOURCE_TYPE_FAV -> {
                favourite = intent.getParcelableExtra(EXTRA_FAVOURITE)
                supportActionBar?.title = favourite!!.name
                favourite!!.addOnVmPreparedListener(this)
            }
        }

        createTimerTask()

        prepareOnDownloadListener()

        viewPager = container
        tabLayout = tabs
        sectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager, null)


        if (sourceType == SOURCE_TYPE_FAV) {
            favourite!!.registerOnVm(receiver)
        }

        thread {
            if (sourceType == SOURCE_TYPE_STOP) {
                @Suppress("UNCHECKED_CAST")
                sectionsPagerAdapter!!.departures = Departure.createDepartures(stopId!!) as HashMap<String, ArrayList<Departure>>
            } else {
                @Suppress("UNCHECKED_CAST")
                sectionsPagerAdapter!!.departures = favourite!!.allDepartures() as HashMap<String, ArrayList<Departure>>
            }
            runOnUiThread {
                sectionsPagerAdapter?.notifyDataSetChanged()
            }
        }

        viewPager!!.adapter = sectionsPagerAdapter
        viewPager!!.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(tabLayout))
        tabLayout.addOnTabSelectedListener(TabLayout.ViewPagerOnTabSelectedListener(viewPager))

        selectTodayPage()

        scheduleRefresh()

        showFab()
    }

    private fun getFavouriteDepartures() {
        thread {
            @Suppress("UNCHECKED_CAST")
            sectionsPagerAdapter!!.departures = favourite!!.allDepartures() as HashMap<String, ArrayList<Departure>>
        }
        runOnUiThread {
            sectionsPagerAdapter?.notifyDataSetChanged()
        }
    }

    override fun onVmPrepared() {
        getFavouriteDepartures()
    }

    private fun showFab() {
        if (sourceType == SOURCE_TYPE_FAV)
            return

        val favourites = FavouriteStorage.getFavouriteStorage(context)
        if (!favourites.has(stopSymbol!!)) {
            fab.setImageDrawable(ResourcesCompat.getDrawable(context.resources, R.drawable.ic_favourite_empty, this.theme))
        }

        fab.setOnClickListener {
            if (!favourites.has(stopSymbol!!)) {
                val items = HashSet<Plate>()
                timetable.getLines(stopId!!).forEach {
                    val o = Plate(it, stopId!!, null)
                    items.add(o)
                }
                favourites.add(stopSymbol as String, items)
                fab.setImageDrawable(ResourcesCompat.getDrawable(context.resources, R.drawable.ic_favourite, this.theme))
            } else {
                Snackbar.make(it, getString(R.string.stop_already_fav), Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show()
            }
        }
    }

    private fun createTimerTask() {
        timerTask = object : TimerTask() {
            override fun run() {
                val vmIntent = Intent(context, VmClient::class.java)
                vmIntent.putExtra(VmClient.EXTRA_STOP_SYMBOL, stopSymbol)
                vmIntent.putExtra(VmClient.EXTRA_REQUESTER, REQUESTER_ID)
                vmIntent.putExtra(VmClient.EXTRA_ID, "stop-${vmRequestId++}")
                startService(vmIntent)
                runOnUiThread {
                    sectionsPagerAdapter?.notifyDataSetChanged()
                }
            }
        }
    }

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

    override fun onVm(vmDepartures: ArrayList<Departure>?, requester: String, id: String, size: Int) {
        if (timetableType == "departure" && requester == REQUESTER_ID && sourceType == SOURCE_TYPE_STOP) {
            @Suppress("UNCHECKED_CAST")
            val fullDepartures = Departure.createDepartures(stopId!!) as HashMap<String, ArrayList<Departure>>
            if (vmDepartures != null) {
                fullDepartures[today.getMode()] = vmDepartures
            }
            sectionsPagerAdapter?.departures = fullDepartures
            sectionsPagerAdapter?.notifyDataSetChanged()
        }
        if (timetableType == "departure" && requester == REQUESTER_ID && sourceType == SOURCE_TYPE_FAV) {
            getFavouriteDepartures()
        }
    }

    private fun selectTodayPage() {
        when (today.get(Calendar.DAY_OF_WEEK)) {
            Calendar.SATURDAY -> tabLayout.getTabAt(1)?.select()
            Calendar.SUNDAY -> tabLayout.getTabAt(2)?.select()
            else -> tabLayout.getTabAt(0)?.select()
        }
    }

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

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

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

        if (id == R.id.action_change_type) {
            if (timetableType == "departure") {
                timetableType = "full"
                item.icon = (ResourcesCompat.getDrawable(resources, R.drawable.ic_timetable_departure, this.theme))
                @Suppress("UNCHECKED_CAST")
                if (sourceType == SOURCE_TYPE_STOP)
                    sectionsPagerAdapter?.departures = timetable.getStopDepartures(stopId!!) as HashMap<String, ArrayList<Departure>>
                else
                    sectionsPagerAdapter?.departures = favourite!!.fullTimetable() as HashMap<String, ArrayList<Departure>>
                sectionsPagerAdapter?.relativeTime = false
                sectionsPagerAdapter?.notifyDataSetChanged()
                timer.cancel()
            } else {
                timetableType = "departure"
                item.icon = (ResourcesCompat.getDrawable(resources, R.drawable.ic_timetable_full, this.theme))
                @Suppress("UNCHECKED_CAST")
                if (sourceType == SOURCE_TYPE_STOP)
                    sectionsPagerAdapter?.departures = Departure.createDepartures(stopId!!) as HashMap<String, ArrayList<Departure>>
                else
                    sectionsPagerAdapter?.departures = favourite!!.allDepartures() as HashMap<String, ArrayList<Departure>>
                sectionsPagerAdapter?.relativeTime = true
                sectionsPagerAdapter?.notifyDataSetChanged()
                scheduleRefresh()
            }
            return true
        }

        return super.onOptionsItemSelected(item)
    }

    override fun onDestroy() {
        super.onDestroy()
        receiver.removeOnVmListener(context as MessageReceiver.OnVmListener)
        unregisterReceiver(receiver)
        timer.cancel()
    }

    class PlaceholderFragment : Fragment() {

        override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                                  savedInstanceState: Bundle?): View? {
            val rootView = inflater!!.inflate(R.layout.fragment_stop, container, false)

            val layoutManager = LinearLayoutManager(activity)
            val departuresList: RecyclerView = rootView.findViewById(R.id.departuresList)
            departuresList.addItemDecoration(DividerItemDecoration(departuresList.context, layoutManager.orientation))

            val departures = arguments.getStringArrayList("departures")?.map { Departure.fromString(it) }
            departuresList.adapter = DeparturesAdapter(activity, departures,
                    arguments["relativeTime"] as Boolean)
            departuresList.layoutManager = layoutManager
            return rootView
        }

        companion object {
            private val ARG_SECTION_NUMBER = "section_number"

            fun newInstance(sectionNumber: Int, departures: ArrayList<Departure>?, relativeTime: Boolean):
                    PlaceholderFragment {
                val fragment = PlaceholderFragment()
                val args = Bundle()
                args.putInt(ARG_SECTION_NUMBER, sectionNumber)
                if (departures != null) {
                    val d = ArrayList<String>()
                    departures.mapTo(d) { it.toString() }
                    args.putStringArrayList("departures", d)
                } else
                    args.putStringArrayList("departures", null)
                args.putBoolean("relativeTime", relativeTime)
                fragment.arguments = args
                return fragment
            }
        }
    }

    inner class SectionsPagerAdapter(fm: FragmentManager, var departures: HashMap<String, ArrayList<Departure>>?) : FragmentStatePagerAdapter(fm) {

        var relativeTime = true

        override fun getItemPosition(obj: Any?): Int {
            return PagerAdapter.POSITION_NONE
        }

        override fun getItem(position: Int): Fragment {
            var mode: String? = null
            when (position) {
                0 -> mode = Timetable.MODE_WORKDAYS
                1 -> mode = Timetable.MODE_SATURDAYS
                2 -> mode = Timetable.MODE_SUNDAYS
            }
            return PlaceholderFragment.newInstance(position + 1, departures?.get(mode), relativeTime)
        }

        override fun getCount() = 3
    }
}