import Foundation
import FBSDKShareKit
import Pods_UnityFramework

@objc public class FBShareHelper : NSObject{

    @objc public func FBShare(title: String, content:String, link : String){
        guard let url = URL(string: link) else
        {
            NSLog("url faild")
            return
        }
        let vc = UnityFramework.getInstance().appController().rootViewController

        let c =  ShareLinkContent()
        c.quote = content
        c.contentURL = url

        let dialog = ShareDialog(
            viewController: vc,
            content: c,
            delegate: FBShareHelperDelegate()
        )
        NSLog("show fb share dialog")
        // Recommended to validate before trying to display the dialog
        do {
            try dialog.validate()
        } catch {
            print("fbshare faild ! \(error)")
        }
        dialog.show()
    }
    
    @objc public func MFBShare(title: String, content:String, link : String){
        guard let url = URL(string: link) else
        {
            NSLog("url faild")
            return
        }
        
        let c =  ShareLinkContent()
        c.quote = content
        c.contentURL = url
        
        let dialog = MessageDialog(content: c, delegate: FBShareHelperDelegate())
        
        do {
            try dialog.validate()
        } catch {
            print("messenger share faild ! \(error)")
        }
        
        if(dialog.canShow)
        {
            dialog.show();
        }
        else
        {
            print("messenger share faild !")
        }
    }
}

class FBShareHelperDelegate: SharingDelegate
{
    public func sharer(_ sharer: any FBSDKShareKit.Sharing, didCompleteWithResults results: [String : Any]) {
        print("Share success \(results)")
        SendToUnity(success: true)
    }
    
    public func sharer(_ sharer: any FBSDKShareKit.Sharing, didFailWithError error: any Error) {
        print("Share error \(error)")
        SendToUnity(success: false)
    }
    
    public func sharerDidCancel(_ sharer: any FBSDKShareKit.Sharing) {
        print("Share cancel")
        SendToUnity(success: false)
    }
    
    private func SendToUnity(success:Bool)
    {
        let message = success ? "0" : "1"
        UnityFramework.getInstance().sendMessageToGO(withName: "GameObje", functionName: "Func", message: message)
    }
    
}

