package com.pan_american.android.ui.message

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.base.BaseFragment
import com.pan_american.android.data.model.message.entity.MessageGetter
import com.pan_american.android.data.model.message.network.MessageUnReadCountRequest
import com.pan_american.android.data.model.message.network.MessageUnReadCountResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentMessageBinding
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class MessageFragment : BaseFragment<FragmentMessageBinding>() {

    companion object {
        const val TASK_MESSAGE_ID = 1020
        const val GROUP_MESSAGE_ID = 1021
    }

    private var taskMessageUnReadCount = 0

    private var groupMessageUnReadCount = 0

    private val apiService = ServiceCreator.create<APIService>()

    override fun getViewBinding(
        inflater: LayoutInflater, container: ViewGroup?, bundle: Bundle?
    ) = FragmentMessageBinding.inflate(inflater, container, false)

    override fun onStart() {
        super.onStart()

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }

        getMessageCount()
    }

    override fun onPause() {
        super.onPause()

        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

    override fun initViews() {
        binding.taskCount.apply {
            if (taskMessageUnReadCount != 0) {
                visibility = View.VISIBLE
                if (taskMessageUnReadCount >= 100) {
                    text = resources.getString(R.string.message_max_count)
                    return@apply
                }
                text = taskMessageUnReadCount.toString()
            } else {
                visibility = View.GONE
            }
        }

        binding.groupCount.apply {
            if (groupMessageUnReadCount != 0) {
                visibility = View.VISIBLE
                if (groupMessageUnReadCount >= 100) {
                    text = resources.getString(R.string.message_max_count)
                    return@apply
                }
                text = groupMessageUnReadCount.toString()
            } else {
                visibility = View.GONE
            }
        }
    }

    override fun initEvents() {
        binding.taskOperationNotification.setOnClickListener {
            val intent = Intent(OASystem.context, MessageListActivity::class.java).apply {
                putExtra("message_type", TASK_MESSAGE_ID)
                if (taskMessageUnReadCount > 0) {
                    putExtra("haveUnread", 2)
                } else {
                    putExtra("haveUnread", 3)
                }
            }

            startActivity(intent)
        }

        binding.groupOperationNotification.setOnClickListener {
            val intent = Intent(OASystem.context, MessageListActivity::class.java).apply {
                putExtra("message_type", GROUP_MESSAGE_ID)
                if (groupMessageUnReadCount > 0) {
                    putExtra("haveUnread", 2)
                } else {
                    putExtra("haveUnread", 3)
                }
            }

            startActivity(intent)
        }
    }

    private fun getMessageCount() {
        if (!isAdded) {
            return
        }

        apiService.getMessageUnReadCount(MessageUnReadCountRequest())
            .enqueue(object : Callback<MessageUnReadCountResponse> {
                override fun onResponse(
                    call: Call<MessageUnReadCountResponse>,
                    response: Response<MessageUnReadCountResponse>
                ) {
                    val dataResponse = response.body()

                    if (dataResponse != null) {
                        if (dataResponse.code == 200) {

                            for (item in dataResponse.data) {
                                when (item.id) {
                                    TASK_MESSAGE_ID -> {
                                        taskMessageUnReadCount = item.unReadCount
                                    }

                                    GROUP_MESSAGE_ID -> {
                                        groupMessageUnReadCount = item.unReadCount
                                    }
                                }
                            }

                            initViews()

                            initEvents()

                        } else {
                            showMessage(dataResponse.msg)
                        }
                    }
                }

                override fun onFailure(call: Call<MessageUnReadCountResponse>, t: Throwable) {
                    showMessage(resources.getString(R.string.network_error))
                }
            })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getMessageUnReadCount(messageGetter: MessageGetter) {
        if (messageGetter.message.isNotBlank()) {
            getMessageCount()
        }
    }
}