package com.halo.assistant.fragment.reserve

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import com.gh.gamecenter.common.utils.CalendarEventUtils
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.common.utils.toRequestBody
import com.gh.gamecenter.entity.ReserveModifyEntity
import com.gh.gamecenter.entity.ReserveReminderEntity
import com.gh.gamecenter.entity.ValidateCodeRequest
import com.gh.gamecenter.entity.ValidateCodeResponse
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.gh.gamecenter.retrofit.service.ApiService
import com.halo.assistant.HaloApp
import io.reactivex.Single
import io.reactivex.schedulers.Schedulers
import okhttp3.RequestBody
import okhttp3.ResponseBody

class ReserveReminderRepository(
    private val apiService: ApiService
) {

    private val handler = object : Handler(Looper.getMainLooper()) {

        @SuppressLint("CheckResult")
        override fun handleMessage(msg: Message) {
            if (msg.what == MESSAGE_WHAT_ENABLE_AUTO_DOWNLOAD) {
                val content = msg.obj as? Pair<GameEntity?, Boolean> ?: return
                val (game, isEnable) = content
                val body = hashMapOf(
                    "wifi_auto_download" to isEnable
                ).toRequestBody()

                val buttonName = if (isEnable) {
                    "勾选自动下载"
                } else {
                    "取消勾选自动下载"
                }
                SensorsBridge.trackAppointmentSuccessDialogClick(
                    game?.id ?: "",
                    game?.name ?: "",
                    game?.categoryChinese ?: "",
                    buttonName
                )
                apiService.reserveModify(game?.id, body)
                    .subscribeOn(Schedulers.io())
                    .subscribe({}, {})
            }
        }
    }

    fun sendVerifyCode(mobile: String): Single<ValidateCodeResponse> =
        apiService.getValidateCode(hashMapOf("mobile" to mobile))

    fun bindPhone(gameId: String, phone: String): Single<ReserveModifyEntity> {
        val body = hashMapOf<String, Any>(
            "sms_config" to ReserveReminderEntity.SmsConfig(true, phone)
        ).toRequestBody()
        return apiService.reserveModify(gameId, body)
    }

    fun verifyPhoneNumber(phoneNumber: String, code: String, serviceId: String): Single<ResponseBody> {
        val request = ValidateCodeRequest(phoneNumber, serviceId, code)
        return apiService.mobileValidate(request)
    }

    fun unableSmsReminder(gameId: String): Single<ReserveModifyEntity> {
        val body = hashMapOf(
            "sms_config" to hashMapOf("notice" to false)
        ).toRequestBody()
        return apiService.reserveModify(gameId, body)
    }

    /**
     * 为防止用户快速点击，这里300ms之内只会请求一次接口
     */
    fun enableAutoDownload(game: GameEntity?, enable: Boolean) {
        val message = Message.obtain()
        message.what = MESSAGE_WHAT_ENABLE_AUTO_DOWNLOAD
        message.obj = game to enable
        handler.removeMessages(MESSAGE_WHAT_ENABLE_AUTO_DOWNLOAD)
        handler.sendMessageDelayed(message, 300)
    }

    fun enableAutoDownloadInBatches(requestBody: RequestBody): Single<ResponseBody> {
        return apiService.reserveSetting(requestBody)
    }

    fun cancelReserveInBatch(requestBody: RequestBody): Single<ResponseBody> {
        return apiService.reserveSetting(requestBody)
    }

    @SuppressLint("CheckResult")
    fun addCalendarEvent(gameId: String, calendarConfig: ReserveReminderEntity.CalendarConfig) =
        Single.create {
            val calendarEvent = CalendarEventUtils.CalendarEvent(
                title = calendarConfig.title,
                startTime = calendarConfig.timeStart * 1000,
                endTIme = calendarConfig.timeEnd * 1000,
                reminderTime = calendarConfig.advanceSeconds * 1000,
                remark = calendarConfig.remark
            )

            val eventId = CalendarEventUtils.addCalendarEvent(calendarEvent, HaloApp.getInstance())
            if (eventId != null) {
                it.onSuccess(eventId)
            } else {
                it.onError(Throwable(message = "Failed to add calendar event"))
            }
        }.doOnSuccess {
            val body = hashMapOf(
                "calendar_config" to hashMapOf("notice" to true)
            ).toRequestBody()
            apiService.reserveModify(gameId, body)
                .subscribe({}, {})
        }

    companion object {

        private const val MESSAGE_WHAT_ENABLE_AUTO_DOWNLOAD = 1

        fun newInstance() =
            ReserveReminderRepository(RetrofitManager.getInstance().newApi)
    }
}