package com.sybotan.android.demo.tools;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.sybotan.android.demo.retrofit.Constant;
import com.yuyh.library.imgsel.utils.LogUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

/**
 * @author wangjie
 * @date 2020.06.13
 * 不基于任何Activity的网络请求发送
 * 本地离线缓存的各种数据发送至服务器
 */
public class OfflineSendRequest {
    private Gson mGson;

    public OfflineSendRequest() {
        mGson = new Gson();
    }


    /**
     * 新的离线图片存储上传
     *
     * @param context
     */
    public void uploadImageNew(Context context) {
        String imageFilePath = LocalDataOperation.getInstance().getOfflineImageFilePath(context);
        File imageFile = new File(imageFilePath);
        if (imageFile.exists()) {
            File[] files = imageFile.listFiles();
            if (files != null && files.length > 0) {
                for (File file : files) {
                    if (!TextUtils.isEmpty(file.getName()) && !file.getName().startsWith("uploaded")) {
                        final String url = Constant.ServerImgIPUp + file.getName();
                        Log.e("uploadImageNew url", url);
                        String result = UploadImage.uploadFiles(file, url);
                        if (!TextUtils.isEmpty(result)) {
                            String resultString = null;
                            try {
                                JSONObject object = new JSONObject(result);
                                resultString = object.getString("Result");
                                Log.e("resultString", resultString);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            if ("success".equals(resultString)) {
                                //不管是那种情况,只要成功都需要从本地删除该图片
                                boolean b = file.renameTo(new File(imageFilePath + File.separator + "uploaded" + file.getName()));
                                //file.delete();
                                LogUtils.e("uploadImageNew", "上传成功" + b + file.getName());
                            } else {
                                LogUtils.e("uploadImageNew", "上传失败");
                            }
                        }
                    }
                }
            }
        }
    }
}