package kr.co.vividnext.sodalive.explorer.profile

import android.content.Intent
import android.widget.Toast
import com.orhanobut.logger.Logger
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kr.co.vividnext.sodalive.base.BaseActivity
import kr.co.vividnext.sodalive.common.LoadingDialog
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
import kr.co.vividnext.sodalive.databinding.ActivityCreatorNoticeWriteBinding
import kr.co.vividnext.sodalive.explorer.ExplorerRepository
import org.koin.android.ext.android.inject

class CreatorNoticeWriteActivity : BaseActivity<ActivityCreatorNoticeWriteBinding>(
    ActivityCreatorNoticeWriteBinding::inflate
) {

    private val repository: ExplorerRepository by inject()

    private lateinit var loadingDialog: LoadingDialog

    override fun setupView() {
        loadingDialog = LoadingDialog(this, layoutInflater)
        binding.toolbar.tvBack.text = "공지사항 쓰기"
        binding.toolbar.tvBack.setOnClickListener { finish() }

        val notice = intent.getStringExtra("notice")
        binding.etContent.setText(notice)

        binding.tvSave.setOnClickListener {
            loadingDialog.show(screenWidth)

            val writtenNotice = binding.etContent.text.toString()
            compositeDisposable.add(
                repository.writeCreatorNotice(
                    notice = writtenNotice,
                    token = "Bearer ${SharedPreferenceManager.token}"
                )
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                        {
                            loadingDialog.dismiss()

                            val message = it.message ?: "알 수 없는 오류가 발생했습니다. 다시 시도해 주세요."
                            Toast.makeText(
                                applicationContext,
                                message,
                                Toast.LENGTH_LONG
                            ).show()

                            if (it.success) {
                                val dataIntent = Intent()
                                dataIntent.putExtra("notice", writtenNotice)
                                setResult(RESULT_OK, dataIntent)
                                finish()
                            }
                        },
                        {
                            loadingDialog.dismiss()
                            it.message?.let { message -> Logger.e(message) }
                            Toast.makeText(
                                applicationContext,
                                "알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.",
                                Toast.LENGTH_LONG
                            ).show()
                        }
                    )
            )
        }
    }
}
