package com.zhaohaoting.framework.mvchelper.okhttp.okhttp;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

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

import okhttp3.Response;

/**
 * author：Created by ZHT on 2017/11/2 10:32
 * email：526309416@qq.com
 * desc：文件的简单下载
 */
public class DownloadFile {

    private String fileDir;
    private String fileName;
    private DownloadCallBack downloadCallBack;

    public DownloadFile(String fileDir, String fileName, DownloadCallBack downloadCallBack) {
        this.fileDir = fileDir;
        this.fileName = fileName;
        this.downloadCallBack = downloadCallBack;
    }

    private Handler mDelivery = new Handler(Looper.getMainLooper());

    public void downloadAsyn(Response response) {
        InputStream is = null;
        long currentLen = 0;
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream fos = null;

        /** 从请求头中读取文件长度 */
        String contentLength = response.header("Content-Length");
        long length = Long.parseLong(TextUtils.isEmpty(contentLength) ? "0" : contentLength);
        try {
            is = response.body().byteStream();
            File file = new File(fileDir, fileName);
            if (file.exists() && file.length() == length) {//若本地存在当前下载文件，且文件大小一致（说明是同一个文件）则，无需再向磁盘写入
                if (is != null) is.close();
                threadMainSuccess(file.getAbsolutePath(), length);
                return;
            } else {
                file.delete();//删除之前破损文件，重新写入
            }
            fos = new FileOutputStream(file);
            while ((len = is.read(buf)) != -1) {
                fos.write(buf, 0, len);
                currentLen += len;
                threadMainProgress(currentLen, length);
            }
            fos.flush();
            //如果下载文件成功，第一个参数为文件的绝对路径
            threadMainSuccess(file.getAbsolutePath(), length);
        } catch (Exception e) {
            threadMainFailure(e);
        } finally {
            try {
                if (is != null) is.close();
            } catch (Exception e) {
            }
            try {
                if (fos != null) fos.close();
            } catch (Exception e) {
            }
        }
    }

    public void threadMainSuccess(final String fileLocalPath, final long contentLength) {
        mDelivery.post(new Runnable() {
            @Override
            public void run() {
                downloadCallBack.success(fileLocalPath, contentLength);
            }
        });
    }

    public void threadMainFailure(final Exception e) {
        mDelivery.post(new Runnable() {
            @Override
            public void run() {
                downloadCallBack.fault(e);
            }
        });
    }

    public void threadMainProgress(final long current, final long total) {
        mDelivery.post(new Runnable() {
            @Override
            public void run() {
                downloadCallBack.progress(current, total);
            }
        });
    }
}
