package com.xypower.common;

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

import org.w3c.dom.Text;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.util.zip.GZIPInputStream;

public class FileDownloader {
    public boolean download(String urlString, String filePath) {
        File downloadFile = null;
        if (TextUtils.isEmpty(urlString))
            return false;
        HttpURLConnection connection = null;
        GZIPInputStream gZIPInputStream = null;
        InputStream is = null;
        OutputStream os = null;
        boolean res = false;

        try {
            Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
            URL url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Accept-Encoding", "gzip");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(60000);
            connection.setDoInput(true);
            connection.connect();
            final File temp = new File(filePath);
            if (temp.exists())
                temp.delete();
            temp.createNewFile();
            temp.setReadable(true, false);
            temp.setWritable(true, false);
            downloadFile = temp;
            Log.d("download", "url " + urlString + "\n save to " + temp);
            os = new FileOutputStream(temp);

            String encoding = connection.getContentEncoding();
            is = connection.getInputStream();

            byte[] buf = new byte[8 * 1024];

            if(TextUtils.equals(encoding, "gzip")) {
                gZIPInputStream = new GZIPInputStream(is);
                is = gZIPInputStream;
            }
            int len;
            try {
                while ((len = is.read(buf)) != -1) {
                    os.write(buf, 0, len);
                }
                os.flush();
                res = true;
            }catch(Exception ex) {
                ex.printStackTrace();
            } finally {
            }
            // Log.d("Download", "download complete url=" + urlString + ", fileSize= " + temp.length());
        } catch (Exception e) {
            // Log.w("downloadAPK", e);
            if (downloadFile != null)
                downloadFile.delete();
            e.printStackTrace();
        } finally {
            closeSilently(os);
            closeSilently(is);
            if (connection != null)
                connection.disconnect();
        }

        return res;
    }

    public static final void closeSilently(Object closeable) {
        try {
            if (closeable != null) {
                if (closeable instanceof Closeable) {
                    ((Closeable) closeable).close();
                } else if (closeable instanceof Socket) {
                    ((Socket) closeable).close();
                } else if (closeable instanceof ServerSocket) {
                    ((ServerSocket) closeable).close();
                } else {
                    throw new IllegalArgumentException("Unknown object to close");
                }
            }
        } catch (IOException e) {
            // ignore
        }
    }
}
