package com.wdkl.lcd_board.helper;

import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.wdkl.lcd_board.helper.AppUpdateHelper.FILE_APK_NAME;
import static com.wdkl.lcd_board.helper.AppUpdateHelper.FILE_APK_PATH;

public class HttpHelper {
    private final static String TAG = "HttpHelper";

    /**
     * @param url   服务器地址
     * @param file  所要上传的文件
     */
    public static void upload(String url, File file, UploadCallback callback) {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file))
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (callback != null) {
                    callback.onFail();
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "upload file response: " + response.toString());
               if( response.code()==200 && response.body() != null) {
                   String data = response.body().string();
                   //voice msg response: upload/file/202104102037715.mp3
                   if (callback != null) {
                       callback.onSuccess(data);
                   }
               } else {
                   if (callback != null) {
                       callback.onFail();
                   }
               }
            }
        });
    }

    public static void download(String url, final DownloadListener listener) {
        Request request = new Request.Builder().url(url).build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("download", "onFailure==" + e.toString());
                if (listener != null) {
                    listener.onDownloadFailed(); // 下载失败
                }
            }

            @Override
            public void onResponse(Call call, Response response) {
                Log.d("download", "response==" + response.body().contentLength());
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(isHaveExistDir(new File(FILE_APK_PATH), new File(FILE_APK_PATH + "/" + FILE_APK_NAME)), FILE_APK_NAME);
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum = sum + (long) len;
                        //int progress = (int) (sum * 1.0f / total * 100);
                        float sp = (float) sum / (float) total;
                        int progress = (int) (sp * 100);
                        Log.d("download", "progress==" + progress);
                        if (listener != null) {
                            listener.onDownloading(progress);// 下载中
                        }
                    }
                    fos.flush();
                    if (listener != null) {
                        listener.onDownloadSuccess(); // 下载完成
                    }
                } catch (Exception e) {
                    Log.d("download", "Exception==");
                    if (listener != null) {
                        listener.onDownloadFailed();
                    }
                } finally {
                    try {
                        if (is != null)
                            is.close();
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                        Log.d("download", "IOException==");
                    }
                }
            }
        });
    }

    private static String isHaveExistDir(File downloadFile, File sonFile) throws IOException {
        Log.d("download", "downloadFile.mkdirs()==" + downloadFile.mkdirs());
        Log.d("download", "sonFile.mkdir()==" + sonFile.mkdir());
        if (!downloadFile.mkdirs()) {
            downloadFile.createNewFile();
        }
        deleteAPKFile(sonFile);//只要文件名相同就可以自动替换(按道理此处不需要了，但为了保险起见还是先执行删除操作)。
        return downloadFile.getAbsolutePath();
    }

    public static boolean deleteAPKFile(File downloadFile) {
        return downloadFile.delete();
    }


    public interface UploadCallback{
        void onFail();
        void onSuccess(String data);
    }

    public interface DownloadListener {
        /**
         * 下载成功
         */
        void onDownloadSuccess();

        /**
         * @param progress 下载进度
         */
        void onDownloading(int progress);

        /**
         * 下载失败
         */
        void onDownloadFailed();
    }
}
