package com.adealink.weparty.deeplink

import android.app.Activity
import android.content.Intent
import android.net.Uri
import com.adealink.frame.push.manager.pushService
import com.adealink.frame.router.manager.IDeepLinkConfig
import com.adealink.frame.share.data.PARAM_LINK
import com.adealink.frame.util.AppUtil
import com.adealink.weparty.AppModule
import com.adealink.weparty.BuildConfig
import com.adealink.weparty.MainActivity
import com.adealink.weparty.module.account.Account
import com.adealink.weparty.module.account.AccountModule
import com.adealink.weparty.push.PushStatEvent
import java.net.URLDecoder

class DeepLinkConfig: IDeepLinkConfig {
    override fun isLogin(): Boolean {
        return AccountModule.isLogin()
    }

    override fun getLoginRouterPath(): String {
        return Account.Login.PATH
    }

    override fun getHomeRouterPath(): String {
        return AppModule.Main.PATH
    }

    override fun getRoomRouterPath(): String {
        // TODO: 进房路由
        //return Room.Room.PATH
        return ""
    }

    override fun getSplashRouterPath(): String {
        return AppModule.Main.PATH
    }

    override fun isHomeActivityExists(): Boolean {
        return AppUtil.runningActivities.find {
            it.contains(MainActivity::class.java.name)
        } != null
    }

    override fun reportPushClick(intent: Intent) {
        val pushMessage = pushService.getPushMessageFromIntent(intent) ?: return
        PushStatEvent(PushStatEvent.Action.CLICK).apply {
            pushId to "${pushMessage.pushId}"
            type to "${pushMessage.messageType}"
            deeplink to "${pushMessage.deeplink}"
        }.send()
    }

    override fun getDynamicLinkRealUriFromIntent(intent: Intent, callback: (uri: Uri?) -> Unit) {
        // 根据可能出现的uri情况，暂无需再解析Firebase Dynamic Link，这移除了shareManager.handleDynamicLinkIntent方法；
        val link: Uri? = intent.data
        val scheme = link?.scheme ?: ""
        val host = link?.host ?: ""
        var realUri: Uri? = null
        //dynamicLink是以http或者https开头的，真实的deeplink是在key为link的参数下
        if (scheme.startsWith("http") && host == BuildConfig.HTTP_DEEP_LINK_HOST) {
            link?.getQueryParameter(PARAM_LINK)?.let {
                realUri = Uri.parse(URLDecoder.decode(it, "UTF-8"))
            }
        } else {
            realUri = intent.data
        }
        callback(realUri)
    }

    override fun getPushMessageType(intent: Intent): Long? {
        val pushMessage = pushService.getPushMessageFromIntent(intent) ?: return null
        return pushMessage.messageType
    }

    override fun getDispatchPathKey(): String {
        return "key_dispatch_path"
    }

    override fun getAuthRedirectUrl(): String {
        return "${BuildConfig.HTTPS_WEB_HOST}${BuildConfig.AUTH_APPLE_PATH}"
    }

    override fun getFromWebUrl(): String {
        return ""
    }

    override fun getCurrentTopActivity(): Activity? {
        return AppUtil.currentActivity
    }
}