package iku.os.net;

import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class TaskInfo {
    private static final String TAG = "IkuClient";
    private static String savePath = "/sdcard/apks/";
    private static String getTaskUrl  = "http://123.56.44.45/tt/ddj/autoApk.do";
    private static String downloadUrl = "http://39.103.73.250/tt/upload/ddj/";
    private static boolean completed = false;

    public static void getTask() {
        new GetTaskAsyncTask().execute();
    }

    private static class GetTaskAsyncTask extends AsyncTask<Void, Void, JSONObject> {
        @Override
        protected JSONObject doInBackground(Void... voids) {
            HttpURLConnection conn = null;
            JSONObject json = null;
            try {
                conn = (HttpURLConnection) new URL(getTaskUrl).openConnection();
                conn.setConnectTimeout(5000);
                conn.setRequestMethod("GET");
                Log.i(TAG, "getTask ResponseCode: " + conn.getResponseCode());
                if (conn.getResponseCode() == 200) {
                    StringBuilder sb = new StringBuilder();
                    try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                        String line;
                        while ((line = br.readLine()) != null) {
                            sb.append(line);
                        }
                    }
                    json = new JSONObject(sb.toString());
                }
            } catch (Exception e) {
                Log.e(TAG, "taskInfo getTask: ", e);
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
            return json;
        }

        @Override
        protected void onPostExecute(JSONObject result) {
            if (result != null) {
                try {
                    int code = result.getInt("code");
                    if (code == 1) {
                        String apkPath = result.getString("apkPath");
                        String packageName = result.getString("packageName");
                        Log.i(TAG, "getTask apkPath: " + apkPath);
                        Log.i(TAG, "getTask packageName: " + packageName);
                        // 拼接URL并启动下载
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                downloadFile(downloadUrl + apkPath, savePath + apkPath);
                                // 执行其他下载操作
                            }
                        }).start();
                    }
                } catch (Exception e) {
                    Log.e(TAG, "Error parsing JSON: ", e);
                }
            }
        }
    }


    public static void downloadFile(String urlStr, String savePath) {
        try (InputStream input = new URL(urlStr).openStream();
             FileOutputStream output = new FileOutputStream(savePath)) {

            byte[] buffer = new byte[1024];
            int bytesRead;

            while ((bytesRead = input.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }
            completed = true;
            Log.i(TAG, "Download completed: " + savePath);
        } catch (IOException e) {
            Log.e(TAG, "Error downloading file: ", e);
        }
    }
}
