package com.yutou.jianr_mg.Tools;

import android.content.Context;

import com.kaopiz.kprogresshud.KProgressHUD;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.yutou.jianr_mg.Application;
import com.yutou.jianr_mg.Data.AppData;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class CDNTools {
    private static CDNTools cdn;
    private UploadManager uploadManager;
    private KProgressHUD hud;
    private Context context;
    public static CDNTools getInstance(Context context){
        if(cdn==null){
            cdn=new CDNTools(context);
        }
        return cdn;
    }
    private CDNTools(Context context){
       this.context=context;
        init();
    }
    private void init(){
        Configuration config = new Configuration.Builder()
                .build();
        uploadManager = new UploadManager(config);
    }

    public void upload(File file,String path,String token){
        hud=Utils.showLoading(context,"正在上传","请稍后");
        hud.show();
        Map<String,String> map=new HashMap<>();
        map.put("x:uToken",AppData.Token);
        map.put("x:uuid",AppData.user.getId()+"");
        map.put("x:qToken",token);
        uploadManager.put(file, path, token, (key, info, response) -> {
            if(info.isOK()){
                Log.i(cdn.getClass().getName(),key+"上传成功");
                Utils.toast(Application.application,"上传完成");
            }else{
                Log.i(cdn.getClass().getName(),"上传失败："+info.error);
            }
            AppData.handler.post(()->hud.dismiss());
        },new UploadOptions(map, null, false, (key, percent) -> {
                hud.setDetailsLabel("正在上传："+percent+"/"+file.length());
        },null));
    }
}
