package com.ccwangluo.ccim.util;

import android.text.TextUtils;

import com.ccwangluo.ccim.CCIMClient;
import com.ccwangluo.ccim.listener.ResultEventCallback;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Logger;

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

public class FileUtils {
    private static final Logger logger = Logger.getLogger(CCIMClient.class.getName());

    public static void uploadFile(String filepath, String url, ResultEventCallback<Void> resultCallback) {
        MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
        OkHttpClient okHttpClient = new OkHttpClient();
        File file = new File(filepath);
        Request request = new Request.Builder()
                .url(url)
                .put(RequestBody.create(mediaType, file))
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                logger.info("upload failure");
                resultCallback.onFailed(ErrorCode.NET_ERROR);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                logger.info("upload success : " + response.toString());
                resultCallback.onSuccess(null);
            }
        });
    }


    public static String renameFile(String oldPath, String newPath, String newFileName) {
        if (TextUtils.isEmpty(oldPath)) {
            return null;
        }

        if (TextUtils.isEmpty(newPath)) {
            return null;
        }
        File oldFile = new File(oldPath);
        File newFile = new File(newPath, newFileName);
        if (oldFile.exists() && oldFile.isFile()) {
            boolean b = oldFile.renameTo(newFile);
        }
        return newFile.getAbsolutePath();
    }

    public static void downLoadFile(String url, File file, ResultEventCallback<File> resultEventCallback) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                logger.info(e.toString());
                resultEventCallback.onFailed(ErrorCode.DOWNLOAD_ERR);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                writeFile(file, response);
                resultEventCallback.onSuccess(file);
            }
        });
    }

    private static void writeFile(File file, Response response) {
        OutputStream outputStream = null;
        InputStream inputStream = response.body().byteStream();
        try {
            outputStream = new FileOutputStream(file);
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
