package cn.yyxx.eyuangame.core.impl.share

import android.app.Activity
import android.content.Intent
import android.net.Uri
import cn.yyxx.eyuangame.base.utils.Logger
import cn.yyxx.eyuangame.core.internal.IImplCallback
import com.facebook.CallbackManager
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.share.Sharer
import com.facebook.share.model.ShareHashtag
import com.facebook.share.model.ShareLinkContent
import com.facebook.share.widget.ShareDialog

/**
 * @author #Suyghur.
 * Created on 2021/09/03
 */
class ShareImpl private constructor() {

    private var shareDialog: ShareDialog? = null
    private var fbCallback: CallbackManager? = null


    init {
        fbCallback = CallbackManager.Factory.create()
    }

    fun invokeShare2Fb(activity: Activity, line: String, tag: String, quote: String, callback: IImplCallback) {
        shareDialog = ShareDialog(activity)
        shareDialog?.registerCallback(fbCallback, object : FacebookCallback<Sharer.Result> {
            override fun onSuccess(result: Sharer.Result?) {
                Logger.d("facebook share onSuccess")
                callback.onResult(0, "facebook share onSuccess")
            }

            override fun onCancel() {
                Logger.d("facebook share onCancel")
                callback.onResult(-1, "facebook share onSuccess")
            }

            override fun onError(error: FacebookException?) {
                Logger.d("facebook share onError")
                callback.onResult(-1, "facebook share onSuccess")
            }
        })

        val shareLinkContent = ShareLinkContent.Builder()
            .setContentUrl(Uri.parse(line))
            .setShareHashtag(ShareHashtag.Builder().setHashtag(tag).build())
            .setQuote(quote)
            .build()
        shareDialog?.show(shareLinkContent)
    }


    fun onShareResult(requestCode: Int, resultCode: Int, intent: Intent?) {
        fbCallback?.onActivityResult(requestCode, resultCode, intent)
    }

    companion object {
        val instance: ShareImpl by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            ShareImpl()
        }
    }
}