Skip to content

Instantly share code, notes, and snippets.

@cbedoy
Created January 29, 2018 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbedoy/061f0eb3df22db19b2a05e9d2cbf79c8 to your computer and use it in GitHub Desktop.
Save cbedoy/061f0eb3df22db19b2a05e9d2cbf79c8 to your computer and use it in GitHub Desktop.
package cbedoy.appluminara.backend.installation
import android.Manifest
import android.annotation.SuppressLint
import android.location.Address
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.OrientationHelper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cbedoy.appluminara.R
import cbedoy.appluminara.backend.installation.InstallationContract.IInstallationPresenter
import cbedoy.appluminara.backend.installation.InstallationContract.IInstallationViewController
import cbedoy.appluminara.common.BaseViewController
import cbedoy.appluminara.common.MessagesRepresentation
import cbedoy.appluminara.common.base.InstallationAdapter
import cbedoy.appluminara.common.base.models.*
import cbedoy.appluminara.common.base.models.base.BaseItem
import cbedoy.appluminara.model.Article
import cbedoy.appluminara.model.Installation
import cbedoy.appluminara.model.Population
import cbedoy.appluminara.model.Project
import com.google.android.gms.location.LocationRequest
import com.patloew.rxlocation.RxLocation
import kotlinx.android.synthetic.main.new_installation_view_controller.*
import pub.devrel.easypermissions.AfterPermissionGranted
import pub.devrel.easypermissions.EasyPermissions
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
import android.content.Intent
import android.net.Uri
/**
* AppLuminara
*
* Created by bedoy on 1/8/18.
*/
class InstallationViewController : BaseViewController(), IInstallationViewController {
private lateinit var mDataModel : ArrayList<Installation>
private lateinit var mViewModel : ArrayList<BaseItem>
lateinit var mPresenter : IInstallationPresenter
private lateinit var mAdapter : InstallationAdapter
private var mValues : List<String>? = null
private var mPopulations: List<Population>? = null
private var mProjects: List<Project>? = null
private var mArticles: List<Article>? = null
lateinit private var currentInstallation : Installation
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.new_installation_view_controller, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val layoutManager = LinearLayoutManager(context)
layoutManager.orientation = OrientationHelper.VERTICAL
mDataModel = ArrayList()
mViewModel = ArrayList()
mAdapter = InstallationAdapter()
mAdapter.viewModel = mViewModel
new_installation_recycler_view.layoutManager = layoutManager
new_installation_recycler_view.adapter = mAdapter
new_installation_recycler_view.setHasFixedSize(true)
}
override fun onResume() {
super.onResume()
currentInstallation = Installation()
currentInstallation.dEmpresaConfiguracionNombre = "FRAGATSA TECNOLOGÍA Y SERVICIOS S.A. DE C.V."
currentInstallation.fLuminariaInstalacionFecha = Date()
runOnAsync("bindArchetype", object :IAsyncProcess{
override fun runOnAsync() {
bindArchetype()
}
})
}
override fun showLoader() {
messagesRepresentation?.showLoader()
}
override fun dismissLoader() {
messagesRepresentation?.dismissLoader()
}
override fun cleanFields() {
runOnAsync("bindArchetype", object :IAsyncProcess{
override fun runOnAsync() {
bindArchetype()
}
})
}
override fun reloadWithData(installation: HashMap<String, Any>) {
}
override fun onLoadedInstallations(installations: ArrayList<Installation>) {
mDataModel.addAll(installations)
dismissLoader()
}
override fun onLoadedInstallation(installation: HashMap<String, Any>?) {
}
override fun onModifiedInstallation(installation: HashMap<String, Any>?) {
}
override fun onDeletedInstallation(installation: HashMap<String, Any>?) {
}
override fun onCreatedInstallation(installation: HashMap<String, Any>?) {
}
private fun prepareHint(identifier : String) = identifier.replace("D_Luminaria_Instalacion_", "").replace("_", "")
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
}
@AfterPermissionGranted(RC_CAMERA_AND_LOCATION)
private fun requestPermission() {
val perms = arrayOf(Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION)
if (EasyPermissions.hasPermissions(context!!, *perms)) {
handleLocationChanges()
} else {
// Do not have permissions, request them now
EasyPermissions.requestPermissions(this, getString(R.string.rationale),
RC_CAMERA_AND_LOCATION, *perms)
}
}
@SuppressLint("MissingPermission")
private fun handleLocationChanges() {
val rxLocation = RxLocation(context!!)
val locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(5000)
rxLocation.location().updates(locationRequest)
.flatMap<Address> { location -> rxLocation.geocoding().fromLocation(location).toObservable() }
.subscribe { address ->
handleAddress(address)
}
}
private fun handleAddress(address: Address?) {
val indexes : ArrayList<Int> = ArrayList()
val latitude = address?.latitude
val longitude = address?.longitude
mViewModel.forEach {
if (it is FieldItem) {
when(it.identifier){
"D_Luminaria_Instalacion_Latitud" -> {
it.value = latitude.toString()
indexes.add(mViewModel.indexOf(it))
}
"D_Luminaria_Instalacion_Longitud" -> {
it.value = longitude.toString()
indexes.add(mViewModel.indexOf(it))
}
}
}
}
activity?.runOnUiThread {
indexes.forEach {
mAdapter.notifyItemChanged(it)
}
}
}
override fun onLoadedPopulations(populations: ArrayList<Population>) {
mPopulations = populations
runOnAsync("loadArticles", object : IAsyncProcess{
override fun runOnAsync() {
mPresenter.loadArticles()
}
})
}
override fun onLoadedArticles(articles: ArrayList<Article>) {
mArticles = articles
runOnAsync("loadValues", object : IAsyncProcess{
override fun runOnAsync() {
mPresenter.loadValues()
}
})
}
override fun onLoadedProjects(projects: ArrayList<Project>) {
mProjects = projects
runOnAsync("loadPopulations", object : IAsyncProcess{
override fun runOnAsync() {
mPresenter.loadPopulations()
}
})
}
companion object {
const val RC_CAMERA_AND_LOCATION = 640
}
@SuppressLint("SimpleDateFormat")
private fun bindArchetype() {
mViewModel.clear()
mViewModel.add(TitleItem(getString(R.string.project)))
mViewModel.add(SelectorItem("Fk_Id_Proyecto", getString(R.string.select_project), null, View.OnClickListener {
val items = ArrayList<String>()
val filteredProject = ArrayList<Project>()
mProjects?.forEach {
if (it.dProyectoNombre != null){
items.add(it.dProyectoNombre!!)
filteredProject.add(it)
}
}
messagesRepresentation?.showSelectorWithTitleAndMessageAndCallback(
getString(R.string.select_project),
items,
object : MessagesRepresentation.IMessagesRepresentationSelectorCallback{
override fun onSelectedSelectorIndex(index: Int) {
handleSelectedProject(filteredProject[index])
}
}
)
}))
val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
simpleDateFormat.timeZone = TimeZone.getTimeZone("UTC")
mViewModel.add(FieldItem("F_Luminaria_Instalacion_Fecha", "Fecha", FieldItem.KIND.STRING, false, simpleDateFormat.format(Date())))
mViewModel.add(TitleItem(getString(R.string.population)))
mViewModel.add(SelectorItem("Fk_Id_Proyecto_Poblacion", getString(R.string.select_population), null, View.OnClickListener {
val items = ArrayList<String>()
val filteredPopulations = ArrayList<Population>()
mPopulations?.forEach {
if (it.dProyectoPoblacionNombre != null){
items.add(it.dProyectoPoblacionNombre!!)
filteredPopulations.add(it)
}
}
messagesRepresentation?.showSelectorWithTitleAndMessageAndCallback(
getString(R.string.select_population),
items,
object : MessagesRepresentation.IMessagesRepresentationSelectorCallback{
override fun onSelectedSelectorIndex(index: Int) {
handleSelectedPopulation(filteredPopulations[index])
}
}
)
}))
mViewModel.add(TitleItem(getString(R.string.new_luminary)))
mViewModel.add(FieldItem("D_Fraccionamiento", getString(R.string.division), FieldItem.KIND.STRING, true, ""))
mViewModel.add(FieldItem("D_Domicilio", getString(R.string.residence), FieldItem.KIND.STRING, true, ""))
mViewModel.add(FieldItem("D_Luminaria_Instalacion_Calle_Colindancia1", getString(R.string.street_coincidence_1), FieldItem.KIND.STRING, true, ""))
mViewModel.add(FieldItem("D_Luminaria_Instalacion_Calle_Colindancia2", getString(R.string.street_coincidence_2), FieldItem.KIND.STRING, true, ""))
mViewModel.add(FieldItem("D_Luminaria_Instalacion_Latitud", getString(R.string.latitude), FieldItem.KIND.LOCATION, false, ""))
mViewModel.add(FieldItem("D_Luminaria_Instalacion_Longitud", getString(R.string.longitude), FieldItem.KIND.LOCATION, false, ""))
mViewModel.add(TitleItem(getString(R.string.new_luminary)))
mViewModel.add(SelectorItem("Fk_Id_Articulo_Config_Actual", getString(R.string.select_new_luminary), null, View.OnClickListener {
val items = ArrayList<String>()
val filteredArticles = ArrayList<Article>()
mArticles?.forEach {
if (it.fkIdArticuloConfig == 31) {
items.add(String.format("${it.dArticuloCodigo!!} - ${it.dArticuloNombre!!}"))
filteredArticles.add(it)
}
}
messagesRepresentation?.showSelectorWithTitleAndMessageAndCallback(
getString(R.string.select_new_luminary),
items,
object : MessagesRepresentation.IMessagesRepresentationSelectorCallback{
override fun onSelectedSelectorIndex(index: Int) {
handleSelectedArticle(filteredArticles[index])
}
}
)
}))
mViewModel.add(FieldItem("D_Luminaria_Instalacion_Orden_Produccion", getString(R.string.production_order), FieldItem.KIND.STRING, true, ""))
mViewModel.add(FieldItem("D_Luminaria_Instalacion_Serie_Actual", getString(R.string.serial_number), FieldItem.KIND.STRING, true, ""))
mViewModel.add(FieldItem("D_Luminaria_Instalacion_Watts_Actual", getString(R.string.new_item_whats), FieldItem.KIND.STRING, false, ""))
mViewModel.add(TitleItem(getString(R.string.old_model)))
mViewModel.add(SelectorItem("Fk_Id_Articulo_Anterior", getString(R.string.select_old_model), null, View.OnClickListener {
val items = ArrayList<String>()
val filteredArticles = ArrayList<Article>()
mArticles?.forEach {
if (it.fkIdArticuloConfig == 32) {
items.add(String.format("${it.dArticuloCodigo!!} - ${it.dArticuloNombre!!}"))
filteredArticles.add(it)
}
}
messagesRepresentation?.showSelectorWithTitleAndMessageAndCallback(
getString(R.string.select_old_model),
items,
object : MessagesRepresentation.IMessagesRepresentationSelectorCallback{
override fun onSelectedSelectorIndex(index: Int) {
handleSelectedOldArticle(filteredArticles[index])
}
}
)
}))
mViewModel.add(FieldItem("D_Luminaria_Instalacion_Watts_Anterior", getString(R.string.old_item_whats), FieldItem.KIND.STRING, false, ""))
mViewModel.add(ActionItem(getString(R.string.update), View.OnClickListener {
prepareNewInstallation()
}))
mViewModel.add(CreditIem(View.OnClickListener {
messagesRepresentation?.showErrorWithTitleAndMessageAndCallback(
"About",
String.format("${getString(R.string.credit)} - by @cbedoy"),
object : MessagesRepresentation.IMessagesRepresentationCallback{
override fun onAccept() {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse("http://cbedoy.github.io/")
startActivity(intent)
}
})
}))
activity?.runOnUiThread {
mAdapter.viewModel = mViewModel
mAdapter.notifyDataSetChanged()
}
mPresenter.loadProjects()
}
private fun handleSelectedProject(project: Project) {
runOnAsync("handleSelectedProject", object : IAsyncProcess{
override fun runOnAsync() {
var index : Int = -1
mViewModel.forEach {
if(it.getType() == BaseItem.TYPES.SELECTOR) {
val selectorItem = it as SelectorItem
if (selectorItem.identifier == "Fk_Id_Proyecto") {
selectorItem.selection = project.dProyectoNombre
currentInstallation.fkIdProyecto = project.fkIdProyecto
currentInstallation.dProyectoNombre = project.dProyectoNombre
currentInstallation.dProyectoIdentifier = project.dProyectoIdentifier
index = mViewModel.indexOf(it)
}
}
}
if (index != -1){
activity?.runOnUiThread {
mAdapter.notifyItemChanged(index)
}
}
}
})
}
private fun handleSelectedPopulation(population: Population) {
runOnAsync("handleSelectedPopulation", object : IAsyncProcess{
override fun runOnAsync() {
var index : Int = -1
mViewModel.forEach {
if(it.getType() == BaseItem.TYPES.SELECTOR){
val selectorItem = it as SelectorItem
if(selectorItem.identifier == "Fk_Id_Proyecto_Poblacion") {
selectorItem.selection = population.dProyectoPoblacionNombre
currentInstallation.fkIdProyectoPoblacion = population.idProyectoPoblacion
currentInstallation.dPoblacionNombre = population.dProyectoPoblacionNombre
index = mViewModel.indexOf(it)
}
}
}
if (index != -1){
activity?.runOnUiThread {
mAdapter.notifyItemChanged(index)
}
}
}
})
}
private fun handleSelectedOldArticle(article: Article) {
runOnAsync("handleSelectedOldArticle", object : IAsyncProcess{
override fun runOnAsync() {
var items : ArrayList<Int> = ArrayList()
mViewModel.forEach {
if(it.getType() == BaseItem.TYPES.SELECTOR){
val selectorItem = it as SelectorItem
if (selectorItem.identifier == "Fk_Id_Articulo_Anterior") {
selectorItem.selection = String.format("${article.dArticuloCodigo} - ${article.dArticuloNombre}")
currentInstallation.fkIdArticuloAnterior = article.idArticulo
currentInstallation.dArticuloIdentifierAnterior = article.dArticuloIdentifier
currentInstallation.dArticuloConfigNombreAnterior = article.dArticuloConfigNombre
currentInstallation.dArticuloCodigoAnterior = article.dArticuloCodigo
items.add(mViewModel.indexOf(it))
}
}else if (it.getType() == BaseItem.TYPES.FIELD){
val fieldItem = it as FieldItem
if (fieldItem.identifier == "D_Luminaria_Instalacion_Watts_Anterior"){
currentInstallation.dLuminariaInstalacionWattsAnterior = article.dArticuloPotencia
}
items.add(mViewModel.indexOf(it))
}
}
activity?.runOnUiThread {
items.forEach {
mAdapter.notifyItemChanged(it)
}
}
}
})
}
private fun handleSelectedArticle(article: Article) {
runOnAsync("handleSelectedArticle", object : IAsyncProcess{
override fun runOnAsync() {
var items : ArrayList<Int> = ArrayList()
mViewModel.forEach {
if(it.getType() == BaseItem.TYPES.SELECTOR){
val selectorItem = it as SelectorItem
if (selectorItem.identifier == "Fk_Id_Articulo_Config_Actual") {
selectorItem.selection = String.format("${article.dArticuloCodigo} - ${article.dArticuloNombre}")
currentInstallation.fkIdArticuloActual = article.idArticulo
currentInstallation.dArticuloIdentifierActual = article.dArticuloIdentifier
currentInstallation.dArticuloConfigNombreActual = article.dArticuloConfigNombre
currentInstallation.dArticuloCodigoActual = article.dArticuloCodigo
items.add(mViewModel.indexOf(it))
}
}else if (it.getType() == BaseItem.TYPES.FIELD){
val fieldItem = it as FieldItem
if (fieldItem.identifier == "D_Luminaria_Instalacion_Watts_Actual"){
currentInstallation.dLuminariaInstalacionWattsActual = article.dArticuloPotencia
}
items.add(mViewModel.indexOf(it))
}
}
activity?.runOnUiThread {
items.forEach {
mAdapter.notifyItemChanged(it)
}
}
}
})
}
private fun prepareNewInstallation() {
val installation : HashMap<String, Any> = HashMap()
mViewModel.forEach {
if (it.getType() == BaseItem.TYPES.FIELD){
val fieldItem = it as FieldItem
installation.put(fieldItem.identifier, fieldItem.value)
}
}
mPresenter.createNewInstallation(installation)
}
override fun onLoadedValues(values: ArrayList<String>) {
mValues = values
runOnAsync("getAllInstallations", object : IAsyncProcess{
override fun runOnAsync() {
mPresenter.getAllInstallations()
}
})
}
override fun showViewController() {
representationHandler?.showViewController(this)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment