using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class SharingManager : MonoBehaviour
{
    public static SharingManager Instance { get; private set; }

    string AndroidURL =
       "https://play.google.com/store/apps/details?id=com.rizze.pipuzzle&hl=en-US&ah=gfIMAf3ZQA42PzRKpRnkmyC0Sek&pli=1";

    string IosURL = "abcd";

    private void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(this);
        }
        else
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
    }
    public void InviteFriends(string InviteURL)
    {
        new NativeShare()
            .SetSubject("Join me in PiPuzzle!")
            .SetText("I'm playing PiPuzzle and it's super fun! Come join me and see how far you can go.")
            .SetUrl(InviteURL)
            .SetCallback((result, shareTarget) =>
                Debug.Log("Invite result: " + result + ", selected app: " + shareTarget))
            .Share();
    }
    public void CopyGameURL()
    {
#if UNITY_ANDROID
        GUIUtility.systemCopyBuffer = AndroidURL;
        Debug.Log("Android platform detected. Play Store link copied to clipboard.");
        InviteFriends(AndroidURL);
#elif UNITY_IOS
        GUIUtility.systemCopyBuffer = IosURL;
        SharingManager.Instance.InviteFriends(IosURL);
        Debug.Log("iOS platform detected. App Store link copied to clipboard.");
#else
        Debug.Log("This platform is not supported for copying the store link.");
#endif
    }

    public void SnapAndShare()
    {
        StartCoroutine(TakeScreenshotAndShare());
    }
    private IEnumerator TakeScreenshotAndShare()
    {
        yield return new WaitForEndOfFrame();

        Texture2D ss = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
        ss.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
        ss.Apply();

        string filePath = Path.Combine(Application.temporaryCachePath, "shared img.png");
        File.WriteAllBytes(filePath, ss.EncodeToPNG());

        // To avoid memory leaks
        Destroy(ss);

        new NativeShare().AddFile(filePath)
            .SetSubject("PiPuzzle!").SetText("Come play PiPuzzle!").SetUrl(AndroidURL)
            .SetCallback((result, shareTarget) => Debug.Log("Share result: " + result + ", selected app: " + shareTarget))
            .Share();

        // Share on WhatsApp only, if installed (Android only)
        //if( NativeShare.TargetExists( "com.whatsapp" ) )
        //	new NativeShare().AddFile( filePath ).AddTarget( "com.whatsapp" ).Share();
    }
}