package iku.os.net;

import android.content.Context;
import android.provider.Settings;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SendResult {

    private Connection _dbConn;
    private final Context _context;
    private final String _appid;
    private final String _downloadUrl;



    public TTTask(Context context, String appid, String downloadUrl) throws Throwable {
        _context = context;
        _appid = appid;
        _downloadUrl = downloadUrl;
    }

    private void saveInfoOfApkADInfo(String packageName, String fileVer, String adVer){
        try {
            File fApp = new File("/data/data/com.bytedance.ttcollector/" + packageName, "ADAPP.txt");
            if (fApp.exists()){
                BufferedReader readerApp = new BufferedReader(new InputStreamReader(new FileInputStream(fApp)));
                String dataContent = readerApp.readLine();
                readerApp.close();

                String sql = "INSERT INTO apkprotocprop (PackageName, Prop, appVer, thirdParty, thirdVer) VALUES(?, ?, ?, ?, ?);";
                //                PreparedStatement ps = _dbConn.prepareStatement(sql);
                //                ps.setString(1, packageName);
                //                ps.setString(2, dataContent);
                //                ps.setString(3, fileVer);
                //                ps.setString(4, "ADJUST");
                //                ps.setString(5, adVer);
                //                ps.executeUpdate();
                //                Log.e("AFTask", "apkprotocprop update ok");
                //                String url = String.format("http://123.56.44.45/tt/manage/apkInfo!addApkProtocPropOp.do?apkProtocProp.packageName=%s&apkProtocProp.appVer=%s&apkProtocProp.thirdParty=%s&apkProtocProp.thirdVer=%s&apkProtocProp.prop=%s", packageName, fileVer, "ADJUST", adVer, dataContent);
                //                System.out.println(url);
                OkHttpClient client = new OkHttpClient();
                FormBody formBody = null;
                JSONObject jsonObject = new JSONObject(dataContent);
                formBody = new FormBody.Builder()
                        .add("apkProtocProp.packageName", packageName)
                        .add("apkProtocProp.appVer", fileVer)
                        .add("apkProtocProp.thirdParty", "ADJUST")
                        .add("apkProtocProp.thirdVer", adVer)
                        .add("apkProtocProp.prop", jsonObject.toString())
                        .build();
                Request request = new Request.Builder()
                        .url("http://123.56.44.45/tt/manage/apkInfo!addApkProtocPropOp.do?")
                        .addHeader("Content-Type", "application/x-www-form-urlencoded")
                        .method("POST", formBody)
                        .build();
                Response response = client.newCall(request).execute();
                if(response.code() == 200) {
                    System.out.println("UpdateOK");
                }
                else {
                    System.out.println("UpdateError");
                }
            }
        }catch (IOException | JSONException e){
            e.printStackTrace();
        }
    }



    private void saveInfoOfApkAFInfo(String packageName, String fileVer, String afVer){
        try {
            File fApp = new File("/data/data/com.bytedance.ttcollector/" + packageName, "AFAPP.txt");
            File fPostT = new File("/data/data/com.bytedance.ttcollector/" + packageName, "AFT.txt");
            File fPostC = new File("/data/data/com.bytedance.ttcollector/" + packageName, "AFCONVERSIONS.txt");
            if (fApp.exists()){
                BufferedReader readerApp = new BufferedReader(new InputStreamReader(new FileInputStream(fApp)));
                String dataContent = readerApp.readLine();
                readerApp.close();
                if (fPostT.exists() || fPostC.exists()){
                    //从服务器读取参数
                    String latestVerOption = queryLatestProp(packageName);
                    dataContent = addAFOption(packageName, latestVerOption, dataContent, fPostC.exists() ? fPostC.getPath() : fPostT.getPath());
                }
                String sql = "INSERT INTO apkprotocprop (PackageName, Prop, appVer, thirdParty, thirdVer) VALUES(?, ?, ?, ?, ?);";
//                PreparedStatement ps = _dbConn.prepareStatement(sql);
//                ps.setString(1, packageName);
//                ps.setString(2, dataContent);
//                ps.setString(3, fileVer);
//                ps.setString(4, "AF");
//                ps.setString(5, afVer);
//                ps.executeUpdate();
//                Log.e("AFTask", "apkprotocprop update ok");
//                String url = String.format("http://123.56.44.45/tt/manage/apkInfo!addApkProtocPropOp.do?apkProtocProp.packageName=%s&apkProtocProp.appVer=%s&apkProtocProp.thirdParty=%s&apkProtocProp.thirdVer=%s&apkProtocProp.prop=%s", packageName, fileVer, "AF", afVer, dataContent);
//                System.out.println(url);
                OkHttpClient client = new OkHttpClient();
                FormBody formBody = null;
                JSONObject jsonObject = new JSONObject(dataContent);
                formBody = new FormBody.Builder()
                        .add("apkProtocProp.packageName", packageName)
                        .add("apkProtocProp.appVer", fileVer)
                        .add("apkProtocProp.thirdParty", "AF")
                        .add("apkProtocProp.thirdVer", afVer)
                        .add("apkProtocProp.prop", jsonObject.toString())
                        .build();
                Request request = new Request.Builder()
                        .url("http://123.56.44.45/tt/manage/apkInfo!addApkProtocPropOp.do?")
                        .addHeader("Content-Type", "application/x-www-form-urlencoded")
                        .method("POST", formBody)
                        .build();
                Response response = client.newCall(request).execute();
                if(response.code() == 200) {
                    System.out.println("UpdateOK");
                }
                else {
                    System.out.println("UpdateError");
                }
            }
        }catch (IOException | JSONException e){
            e.printStackTrace();
        }
    }


    private String addAFOption(String packageName, String latestVerOption, String json, String postFile){
        String result = "";
        try {
            JSONObject target = new JSONObject(json);
            FileReader fileReader = new FileReader(postFile);
            BufferedReader reader = new BufferedReader(fileReader);
            JSONObject option = new JSONObject();

            JSONObject post = new JSONObject(reader.readLine());
            if (post.has("android_id")){
                String android_id = "", current_value = post.getString("android_id");
                try { android_id = Settings.Secure.getString(_context.getContentResolver(), Settings.Secure.ANDROID_ID); }catch (Throwable ex){}
                if (android_id != null && !android_id.isEmpty()) {
                    current_value = current_value.replace(android_id, "{android_id}");
                }
                if (post.has("advertiserId")){
                    String advertiserId = post.getString("advertiserId");
                    current_value = current_value.replace(advertiserId, "{gaid}");
                }
                if (post.has("uid")){
                    String uid = post.getString("uid");
                    current_value = current_value.replace(uid, "{uid}");
                }
                if(!current_value.contains("{")){
                    option.put("manualhandle", true);
                }
                option.put("android_id", current_value);
            }
            if (post.has("appUserId")){
                String android_id = "", current_value = post.getString("appUserId");
                try { android_id = Settings.Secure.getString(_context.getContentResolver(), Settings.Secure.ANDROID_ID); }catch (Throwable ex){}
                if (android_id != null && !android_id.isEmpty()) {
                    current_value = current_value.replace(android_id, "{android_id}");
                }
                if (post.has("advertiserId")){
                    String advertiserId = post.getString("advertiserId");
                    current_value = current_value.replace(advertiserId, "{gaid}");
                }
                if (post.has("uid")){
                    String uid = post.getString("uid");
                    current_value = current_value.replace(uid, "{uid}");
                }
                if(!current_value.contains("{")){
                    option.put("manualhandle", true);
                }
                option.put("appUserId", current_value);
            }
            if (post.has("customData")){
                String android_id = "", current_value = post.getString("customData");
                try { android_id = Settings.Secure.getString(_context.getContentResolver(), Settings.Secure.ANDROID_ID); }catch (Throwable ex){}
                if (android_id != null && !android_id.isEmpty()) {
                    current_value = current_value.replace(android_id, "{android_id}");
                }
                if (post.has("advertiserId")){
                    String advertiserId = post.getString("advertiserId");
                    current_value = current_value.replace(advertiserId, "{gaid}");
                }
                if(!current_value.contains("{")){
                    option.put("manualhandle", true);
                }
                option.put("customData", current_value);
            }
            if (post.has("currency")){
                option.put("currency", post.getString("currency"));
            }
            if (post.has("onelink_id")){
                option.put("onelink_id", post.getString("onelink_id"));
            }
            if (post.has("af_currentstore")){
                option.put("api_store_value", post.getString("af_currentstore"));
            }
//            if (post.has("channel")){
//                option.put("channel", post.getString("channel"));
//            }
//            if (post.has("imei")){
//                option.put("imei", post.getString("imei"));
//            }
//            if (post.has("lvl")){
//                option.put("lvl", true);
//            }

            //比对
            if (latestVerOption != null && latestVerOption.length() != 0) {
                JSONObject latestVerOptionJson = new JSONObject(latestVerOption);
                Iterator<String> it = latestVerOptionJson.keys();
                while (it.hasNext()) {
                    String key = it.next();
//                    Log.d(TAG, "propCorrection: key " + key);
//                    Log.d(TAG, "propCorrection: value " + prop4ServerJson.getString(key));

                    //信任服务器旧版数据模式
//                    if ((!option.has(key)) || option.getString(key).equals("")) {
//                        //propJson.put(key, prop4ServerJson.getString(key));
//                        option.put(key, latestVerOptionJson.get(key));
//                    }

                    //信任自己取到的数据模式
                    if ((option.has(key))) {
                        option.remove(key);
                        option.put(key, latestVerOptionJson.get(key));
                    }
                }
            }

            if (option.length() > 0) {
                //替换uuid android_id gaid
                String optionStr = option.toString();
                optionStr = optionStr.replaceAll("[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}", "{uuid36}");
                optionStr = optionStr.replaceAll("[0-9A-F]{8}(-[0-9A-F]{4}){3}-[0-9A-F]{12}", "{uuid36U}");
                optionStr = optionStr.replaceAll("[0-9a-f]{32}", "{uuid32}");
                optionStr = optionStr.replaceAll("[0-9A-F]{32}", "{uuid32U}");
                optionStr = optionStr.replaceAll("[0-9a-fA-F]{16}", "{android_id}");

                //额外需要修改参数的apk判断
                optionStr = specOption(packageName, optionStr);
                option = new JSONObject(optionStr);
                //prop.put("option", option);
                target.put("option", option);
            }

            result = target.toString();
            reader.close();
            fileReader.close();
        }catch (Throwable e){
            e.printStackTrace();
        }
        return result;
    }


    //特殊APP的option处理
    public static String specOption(String packageName, String optionStr) {
        String specPackageNames = "com.eterno.shortvideos|com.fiverr.fiverr";
        if (specPackageNames.contains(packageName)) {
            JSONObject prop = null;
            try {
                prop = new JSONObject(optionStr);
                if (prop == null) return optionStr;

                switch (packageName) {
                    case "com.eterno.shortvideos":
                        if (prop.has("appUserId")) {
                            prop.put("appUserId", "j.{2}{0}{2}{1}{2}{1}{1}{1}{2}{1}{1}{1}{2}{2}{2}{1}{1}{1}{2}{1}{2}{1}{2}{2}{2}{0}{2}{2}{2}{1}09A");
                        }
                        break;
                    case "com.fiverr.fiverr":
                        if (prop.has("appUserId")) {
                            prop.put("appUserId", "{timestamp13}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}");
                        }
                        break;
                    case "com.neptune.domino":
                        if (prop.has("appUserId")) {
                            prop.put("appUserId", "{4}{4}:{4}{4}:{4}{4}:{4}{4}:{4}{4}:{4}{4}");
                        }
                        break;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            optionStr = prop.toString();
        }
        return optionStr;
    }


    private String queryLatestProp(String packageName) {
        String propString = null;
        int latestVersionCode = 0;
        String optionString = null;

        String sql = "SELECT * FROM apkprotocprop WHERE PackageName = ?;";
        try {
            PreparedStatement ps = _dbConn.prepareStatement(sql);
            ps.setString(1, packageName);
            ResultSet rs = ps.executeQuery();
            while (rs.next()){
                propString =  rs.getString("Prop");
                JSONObject jsonObject = new JSONObject(propString);
                if (jsonObject.has("versionCode")){
                    if (jsonObject.getInt("versionCode") > latestVersionCode){
                        latestVersionCode = jsonObject.getInt("versionCode");
                        if (jsonObject.has("option")){
                            optionString = jsonObject.getString("option");
                        }
                    }
                }
            }
            Log.d("AFTask", "queryLatestProp: " + propString);
        } catch (SQLException | JSONException e) {
            e.printStackTrace();
        }
        Log.e("AFTask", "latestVersionCode: " + latestVersionCode + "  option: " + optionString);
        return optionString;
    }
}
