SHARE
TWEET

Untitled

a guest Aug 13th, 2017 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package chapters.addnewclient
  2.  
  3. import android.Manifest
  4. import android.app.Activity
  5. import android.content.Context
  6. import android.content.Intent
  7. import android.net.Uri
  8. import android.os.Bundle
  9. import android.view.Menu
  10. import android.view.MenuItem
  11. import android.view.inputmethod.InputMethodManager
  12. import chapters.base.BaseActivity
  13. import chapters.base.NetworkMVPView2
  14. import chapters.clients.clients_profile.contacts.ContactsFragment
  15. import chapters.home.HomeActivity
  16. import chapters.recordsbook.recordclient.RecordUserStep2
  17. import com.bumptech.glide.Glide
  18. import com.bumptech.glide.load.engine.DiskCacheStrategy
  19. import com.cookiedev.rooky.R
  20. import com.github.rtoshiro.util.format.SimpleMaskFormatter
  21. import com.jakewharton.rxbinding.widget.textChanges
  22. import com.orhanobut.logger.Logger
  23. import com.tbruyelle.rxpermissions.RxPermissions
  24. import instruments.managers.LoginManager
  25. import jp.wasabeef.glide.transformations.CropCircleTransformation
  26. import kotlinx.android.synthetic.main.activity_add_new_client.*
  27.  
  28. import rx.Observable
  29. import utils.FileUtils
  30. import utils.NUMBER_PREFIX
  31. import utils.PHONE_NUMBER_PATTERN
  32. import utils.createRetryNetObs
  33. import utils.extentions.*
  34. import utils.glide.PhotoDelegate
  35. import utils.text.EditableMaskTextWatcher
  36. import utils.text.getNumber
  37. import java.util.*
  38.  
  39. class AddNewClientActivity : BaseActivity(), NetworkMVPView2<Long>, ContactsFragment.ContactChecked {
  40.  
  41.     companion object {
  42.         private const val KEY_TOKEN = "token"
  43.         private const val KEY_NAME_CLIENT = "name_client"
  44.         private const val KEY_SURNAME_CLIENT = "surname_client"
  45.         private const val KEY_PHONES = "phones"
  46.         private const val ANIMATION_TIME = 260L
  47.         private const val MIN_CHARACTER_NUMBER = 1
  48.         private const val MIN_PHONE_NUMBER_SYMBOLS = 5
  49.  
  50.         fun launch(activity: Activity) {
  51.             activity.startActivity(Intent(activity, AddNewClientActivity::class.java))
  52.             activity.overridePendingTransition(R.anim.right_in, R.anim.left_out)
  53.         }
  54.     }
  55.  
  56.     val photoDelegate by lazy { PhotoDelegate(this) }
  57.     lateinit var presenter: AddNewClientPresenter
  58.     var capturedImageURI: Uri? = null
  59.  
  60.     override fun onCreate(savedInstanceState: Bundle?) {
  61.         super.onCreate(savedInstanceState)
  62.         setContentView(R.layout.activity_add_new_client)
  63.         presenter = AddNewClientPresenter(this)
  64.         btnSave.isEnabled = false
  65.         btnSave.setOnClickListener {
  66.             hideKeyboard()
  67.             val clientParams = HashMap<String, String>()
  68.             clientParams.put(KEY_TOKEN, LoginManager(this).token)
  69.             clientParams.put(KEY_NAME_CLIENT, etName.text.toString())
  70.             clientParams.put(KEY_SURNAME_CLIENT, etSurname.text.toString())
  71.             clientParams.put(KEY_PHONES, getNumber(etPhone.text.toString()))
  72.             val filePath = capturedImageURI?.let { FileUtils.getPath(this, it) }
  73.             presenter.saveClient(clientParams, filePath)
  74.         }
  75.  
  76.         ivPhoto.setOnClickListener {
  77.             photoDelegate.showChooserAlert {
  78.                 loadImage(it)
  79.             }
  80.         }
  81.         etPhone.addTextChangedListener(EditableMaskTextWatcher(etPhone, SimpleMaskFormatter(PHONE_NUMBER_PATTERN)))
  82.         etPhone.setText(NUMBER_PREFIX)
  83.         initEdit()
  84.         setupToolbar()
  85.     }
  86.  
  87.     private fun loadImage(it: Uri?) {
  88.         capturedImageURI = it
  89.         Glide.with(this)
  90.                 .load(it)
  91.                 .skipMemoryCache(true)
  92.                 .diskCacheStrategy(DiskCacheStrategy.NONE)
  93.                 .centerCrop()
  94.                 .bitmapTransform(CropCircleTransformation(this))
  95.                 .placeholder(getDrawableFromVector(R.drawable.ic_ava_place))
  96.                 .into(ivPhoto)
  97.     }
  98.  
  99.     private fun hideKeyboard() {
  100.         val input = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
  101.         input.hideSoftInputFromWindow(rootView.windowToken, 0)
  102.     }
  103.  
  104.     fun initEdit() {
  105.         val nameObserver = etName.textChanges().skip(1)
  106.                 .map { it.length > MIN_CHARACTER_NUMBER }.share()
  107.         compositeSub += nameObserver.subscribe {
  108.             tilName.setErrorMess(it, R.string.msg_add_client_short_name)
  109.         }
  110.         val surnameObserver = etSurname.textChanges().skip(1)
  111.                 .map { it.length > MIN_CHARACTER_NUMBER }.share()
  112.         compositeSub += surnameObserver.subscribe {
  113.             tilSurname.setErrorMess(it, R.string.msg_add_client_short_surname)
  114.         }
  115.         val phoneObserver = etPhone.textChanges().skip(1)
  116.                 .map { it.toString().leftOnlyDigits().length >= MIN_PHONE_NUMBER_SYMBOLS }.distinctUntilChanged().share()
  117.         compositeSub += phoneObserver.subscribe {
  118.             tilPhone.setErrorMess(it, R.string.msg_add_client_wrong_number)
  119.         }
  120.         compositeSub += Observable.combineLatest(nameObserver.startWith(false), surnameObserver.startWith(false), phoneObserver.startWith(false)) { nameIsValid, surnameIsValid, phoneIsValid ->
  121.             Logger.d("$nameIsValid, $surnameIsValid, $phoneIsValid")
  122.             nameIsValid && surnameIsValid && phoneIsValid
  123.         }.subscribe { btnSave.isEnabled = it }
  124.     }
  125.  
  126.     private fun setupToolbar() {
  127.         setSupportActionBar(toolbar)
  128.         supportActionBar?.run {
  129.             setHomeButtonEnabled(true)
  130.             setDisplayHomeAsUpEnabled(true)
  131.             setDisplayShowTitleEnabled(false)
  132.         }
  133.  
  134.     }
  135.  
  136.     override fun onCreateOptionsMenu(menu: Menu): Boolean {
  137.         menuInflater.inflate(R.menu.contacts_single, menu)
  138.         return true
  139.     }
  140.  
  141.     override fun onResult(result: Long) = RecordUserStep2.launch(this, result, HomeActivity.ChildChapter.CLIENT_RECORD)
  142.  
  143.     override fun onRequestBegin() = progress.showAnim(ANIMATION_TIME)
  144.  
  145.     override fun onRequestTerminate() = progress.hide()
  146.  
  147.     override fun onError(throwable: Throwable) = showErrorAlert(throwable)
  148.  
  149.     override fun getRetryObservable(): Observable<Boolean> = createRetryNetObs(rootView)
  150.  
  151.     override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
  152.         super.onActivityResult(requestCode, resultCode, data)
  153.         photoDelegate.onActivityResult(requestCode, resultCode, data)
  154.  
  155.         if (requestCode == AddContactsActivity.REQUEST_CODE) {
  156.             onContactChecked(AddContactsActivity.fromResult(data) ?: return)
  157.         }
  158.     }
  159.  
  160.     override fun onOptionsItemSelected(item: MenuItem): Boolean {
  161.         if (item.itemId == android.R.id.home) finish()
  162.         else if (item.itemId == R.id.action_contacts) {
  163.             compositeSub += RxPermissions(this)
  164.                     .request(Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_EXTERNAL_STORAGE)
  165.                     .subscribe { if (it) { AddContactsActivity.launchForResult(this) } } }
  166.         return true
  167.     }
  168.  
  169.     override fun finish() {
  170.         presenter.unbind()
  171.         super.finish()
  172.         overridePendingTransition(R.anim.left_in, R.anim.right_out)
  173.     }
  174.  
  175.     override fun onContactChecked(contact: ContactsFragment.Contact) {
  176.         val names = contact.name.split(" ")
  177.         if (names.isNotEmpty())
  178.             etName.setText(names[0])
  179.         if (names.size > 1) etSurname.setText(names[1])
  180.         etPhone.setText(contact.phone)
  181.         loadImage(contact.getRealPath(this))
  182.     }
  183. }
RAW Paste Data
Pastebin PRO Summer Special!
Get 40% OFF on Pastebin PRO accounts!
Top