package com.bleplx.adapter;

import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import com.bleplx.adapter.errors.BleError;
import com.bleplx.adapter.errors.BleErrorCode;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class FirmwareDownloadTask extends AsyncTask<String, Void, Uri> {

  private Context mContext;
   private OnSuccessCallback<Uri> onSuccessCallback;
   private OnErrorCallback onErrorCallback;

   private OnSuccessCallback<Integer> onLenCallback;

  public void setmContext(Context mContext) {
    this.mContext = mContext;
  }

  public void setOnSuccessCallback(OnSuccessCallback<Uri> onSuccessCallback) {
    this.onSuccessCallback = onSuccessCallback;
  }

  public void setOnErrorCallback(OnErrorCallback onErrorCallback) {
    this.onErrorCallback = onErrorCallback;
  }


  public void setOnLenCallback(OnSuccessCallback<Integer> onLenCallback) {
    this.onLenCallback = onLenCallback;
  }

  @Override
  protected Uri doInBackground(String... urls) {
    try {
      String urlString = urls[0];
      String path;
      if (Build.VERSION.SDK_INT >= 29) {
        path = mContext.getExternalFilesDir(null).getAbsolutePath();
      } else  {
        path = Environment.getDownloadCacheDirectory().getAbsolutePath();
      }
      String fileName = urlString.substring(urlString.lastIndexOf("/") + 1);
      Log.d("-- custom", "文件名" + fileName);
      String filePath = path + "/" + fileName;
      Log.d("-- custom", "文件路径" + filePath);


      URL url = new URL(urlString);
      URLConnection connection = url.openConnection();
      connection.connect();

      // 获取文件的总字节数
      int fileLength = connection.getContentLength();

      if (onLenCallback != null) {
        onLenCallback.onSuccess(fileLength);
      }

      // 创建输入流来读取文件
      InputStream inputStream = connection.getInputStream();

      int fileSize = connection.getContentLength();
      if (fileSize <= 0) {
        Log.d("-- custom", "无法获取文件大小");
        throw new RuntimeException("无法获取文件大小");
      }
      if (inputStream == null) {
        Log.d("-- custom", "无法获取文件流");
        throw new RuntimeException("无法获取文件流");
      }

      File file = new File(path);
      if (!file.exists()) {
        file.mkdirs();
      }

      FileOutputStream fos = new FileOutputStream(filePath);
      byte[] buffer = new byte[1024];
      int downloadSize = 0;
      do {
        int num = inputStream.read(buffer);
        if (num == -1) {
          break;
        }
        fos.write(buffer, 0, num);
        downloadSize += num;
        Log.d("-- custom", "下载进度" + downloadSize + "/" + fileSize);
      } while (true);

      inputStream.close();
      fos.flush();
      Log.d("-- custom", "下载成功");

      return Uri.fromFile(new File(filePath));
    } catch (Exception e) {
      BleError bleError = new BleError(BleErrorCode.OTAFirmwareErrorDownloadFailed, "固件下载失败", null);
      bleError.internalMessage = e.getMessage();
      Log.d("-- custom", "下载失败" + e.getMessage());
      onErrorCallback.onError(bleError);
    }
    return null;
  }


  @Override
  protected void onPostExecute(Uri result) {
    if (result != null) {
      // 下载成功
      onSuccessCallback.onSuccess(result);
    } else {
      // 下载失败
      BleError bleError = new BleError(BleErrorCode.OTAFirmwareErrorDownloadFailed, "固件下载失败", null);
      onErrorCallback.onError(bleError);
      Log.d("-- custom", "固件下载失败");
    }
  }

}
