package com.tagmae.tsgame_erwang;

import android.util.Log;
import com.tagmae.jsbridge.BridgeWebView;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

/**
 * Canvas转Base64使用示例
 * 展示如何使用WebViewScreenshotUtil中的Canvas相关功能
 */
public class CanvasBase64Example {
    private static final String TAG = "CanvasBase64Example";

    /**
     * 示例1：获取指定ID的Canvas内容
     */
    public static void captureCanvasById(BridgeWebView webView, String canvasId) {
        WebViewScreenshotUtil.getCanvasBase64FromWebView(webView, canvasId, 
            new WebViewScreenshotUtil.CanvasToBase64Callback() {
                @Override
                public void onSuccess(String base64Data) {
                    Log.d(TAG, "Canvas captured successfully! Base64 length: " + base64Data.length());
                    // 在这里处理获取到的base64数据
                    // 例如：保存到文件、上传到服务器、显示在ImageView中等
                    handleBase64Data(base64Data);
                }

                @Override
                public void onError(String error) {
                    Log.e(TAG, "Failed to capture canvas: " + error);
                }
            });
    }

    /**
     * 示例2：获取页面中第一个Canvas内容
     */
    public static void captureFirstCanvas(BridgeWebView webView) {
        WebViewScreenshotUtil.getCanvasBase64FromWebView(webView, null, 
            new WebViewScreenshotUtil.CanvasToBase64Callback() {
                @Override
                public void onSuccess(String base64Data) {
                    Log.d(TAG, "First canvas captured! Base64 length: " + base64Data.length());
                    handleBase64Data(base64Data);
                }

                @Override
                public void onError(String error) {
                    Log.e(TAG, "Failed to capture first canvas: " + error);
                }
            });
    }

    /**
     * 示例3：获取页面中所有Canvas内容
     */
    public static void captureAllCanvas(BridgeWebView webView) {
        WebViewScreenshotUtil.getAllCanvasBase64FromWebView(webView, 
            new WebViewScreenshotUtil.CanvasToBase64Callback() {
                @Override
                public void onSuccess(String jsonResult) {
                    Log.d(TAG, "All canvas captured! JSON result: " + jsonResult);
                    // jsonResult是一个JSON字符串，包含所有Canvas的信息
                    handleAllCanvasData(jsonResult);
                }

                @Override
                public void onError(String error) {
                    Log.e(TAG, "Failed to capture all canvas: " + error);
                }
            });
    }

    /**
     * 示例4：高级Canvas截图 - 自动回退机制
     */
    public static void captureCanvasAdvanced(BridgeWebView webView, String canvasId) {
        WebViewScreenshotUtil.captureCanvasAdvanced(webView, canvasId, 
            new WebViewScreenshotUtil.CanvasToBase64Callback() {
                @Override
                public void onSuccess(String base64Data) {
                    Log.d(TAG, "Advanced canvas capture succeeded! Base64 length: " + base64Data.length());
                    handleBase64Data(base64Data);
                }

                @Override
                public void onError(String error) {
                    Log.e(TAG, "Advanced canvas capture failed: " + error);
                }
            });
    }

    /**
     * 示例5：传统WebView截图转base64
     */
    public static void captureWebViewToBase64(BridgeWebView webView) {
        // 同步方法，直接返回base64字符串
        String base64 = WebViewScreenshotUtil.captureWebViewToBase64(webView);
        if (base64 != null) {
            Log.d(TAG, "WebView captured to base64! Length: " + base64.length());
            handleBase64Data(base64);
        } else {
            Log.e(TAG, "Failed to capture WebView to base64");
        }
    }

    /**
     * 示例6：自定义质量的WebView截图转base64
     */
    public static void captureWebViewToBase64WithQuality(BridgeWebView webView, int quality) {
        String base64 = WebViewScreenshotUtil.captureWebViewToBase64(webView, quality);
        if (base64 != null) {
            Log.d(TAG, "WebView captured with quality " + quality + "! Base64 length: " + base64.length());
            handleBase64Data(base64);
        } else {
            Log.e(TAG, "Failed to capture WebView with quality " + quality);
        }
    }

    /**
     * 处理单个Canvas的base64数据
     */
    private static void handleBase64Data(String base64Data) {
        // 在这里实现你的业务逻辑
        // 例如：
        // 1. 保存到本地文件
        // 2. 上传到服务器
        // 3. 转换为Bitmap显示
        // 4. 分享给其他应用等
        
        Log.d(TAG, "Processing base64 data of length: " + base64Data.length());
        
        // 示例：如果需要转换回Bitmap
        // Bitmap bitmap = base64ToBitmap(base64Data);
    }

    /**
     * 处理所有Canvas的JSON数据
     */
    private static void handleAllCanvasData(String jsonResult) {
        // jsonResult格式示例：
        // [{"index":0,"id":"gameCanvas","width":800,"height":600,"dataUrl":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."}]
        
        Log.d(TAG, "Processing all canvas data: " + jsonResult);
        
        // 可以使用JSON解析库（如Gson）来解析结果
        // 然后分别处理每个Canvas的数据
    }

    /**
     * 工具方法：将base64转换回Bitmap（如果需要的话）
     */
    public static android.graphics.Bitmap base64ToBitmap(String base64) {
        try {
            byte[] decodedBytes = android.util.Base64.decode(base64, android.util.Base64.DEFAULT);
            return android.graphics.BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
        } catch (Exception e) {
            Log.e(TAG, "Error converting base64 to bitmap: " + e.getMessage());
            return null;
        }
    }

    /**
     * 在Activity中的完整使用示例
     */
    public static class ActivityExample {
          public void onWebViewReady(BridgeWebView webView) {
            // 等待WebView加载完成后再进行截图
            webView.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    
                    // 页面加载完成后，稍微延迟一下确保Canvas渲染完成
                    view.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            // 尝试获取特定Canvas
                            captureCanvasById(webView, "gameCanvas");
                            
                            // 或者使用高级方法（推荐）
                            captureCanvasAdvanced(webView, "gameCanvas");
                        }
                    }, 1000); // 延迟1秒
                }
            });
        }
    }
}
