package com.adealink.weparty.webview.scheme

import android.net.Uri
import androidx.core.net.toUri
import com.adealink.frame.router.handler.UriHandler
import com.adealink.frame.router.request.UriRequest
import com.adealink.weparty.BuildConfig
import com.adealink.weparty.webview.IWebView
import com.google.errorprone.annotations.DoNotCall

interface WebScheme {

    interface Common {
        companion object {
            const val SCHEME = BuildConfig.DEEP_LINK_SCHEME
            const val HOST = "web"
        }
    }

    interface CloseWindow {
        companion object {
            const val PATH = "/closeWindow"
        }
    }

    interface UserCancellation {
        companion object {
            const val PATH = "/userCancellation"
        }
    }

    interface OpenNewPage {
        companion object {
            const val PATH = "/page"
        }
    }

    interface PlaymateApply {
        companion object {
            const val PATH = "/playmateApply"
        }
    }

}

abstract class WebSchemeHandler(val webView: IWebView, val paths: Array<String>) : UriHandler() {

    private val schemeUris = mutableSetOf<Uri>()

    init {
        for (path in paths) {
            schemeUris.add("${WebScheme.Common.SCHEME}://${WebScheme.Common.HOST}${path}".toUri())
        }
    }

    override fun canHandle(request: UriRequest): Boolean {
        return paths.contains(request.path)
    }

    @DoNotCall
    override fun handle(request: UriRequest) {
        //Ntd.
    }

    abstract fun handle(uri: Uri)

    companion object {
        @JvmStatic
        fun toUriRequest(uri: Uri): UriRequest {
            val scheme = WebScheme.Common.SCHEME
            val host = WebScheme.Common.HOST
            return UriRequest(path = uri.path?.removePrefix("$scheme://$host") ?: "")
        }
    }

}