package com.qy.ui;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import com.qy.Interfaces.SmaliApkToolsPath;
import com.qy.utils.AutoRandomAdSDK;
import com.qy.utils.SmaliUtils;
import com.qy.utils.Tools;
import org.json.JSONArray;
import org.json.JSONObject;

public class OneWayTools {
	private JSONObject config;
	private String home;
	private String packageName=null;
	private File sdk,core;
	public static void main(String[] args) {
		new OneWayTools(new File("OnewaySdk.jar"));
	}


	public OneWayTools(File onwsdk) {
		// TODO Auto-generated constructor stub
		config= Tools.loadConfig(new File("ad_config.cfg"));
		sdk=new File("Oneway-2.4.3-release.jar");
		JSONArray array=new JSONArray();
		JSONObject gdt = new JSONObject();
		gdt.put("file", "D:\\IDEA\\android_sdk_tools\\Oneway-2.4.3-release.jar");
		gdt.put("version", "5800");
		gdt.put("type", "11");
		gdt.put("index", 2);
		gdt.put("packageName", "com.riboq.qazrj.oo");
		array.put(gdt);
		new AutoRandomAdSDK(array, new SmaliApkToolsPath() {
			@Override
			public void smaliPath(String path) {
				System.out.println(">>:!sdk:"+path);
				start(onwsdk);
			}
		});
	}
	private void start(File onewayjar) {
		core=onewayjar;
		SmaliUtils smali = new SmaliUtils();
		smali.unPack(onewayjar.getAbsolutePath(), new SmaliApkToolsPath() {

			@Override
			public void smaliPath(String path) {
				// TODO Auto-generated method stub
				home=path;
				update(path);

			}
		});
	}

	private void update(String path) {
		File activity = new File(path + File.separator + "smali" + File.separator + "mobi" + File.separator + "oneway"
				+ File.separator + "sdk" + File.separator + "port" + File.separator + "Unit.smali");
		File provider = new File(path + File.separator + "smali" + File.separator + "mobi" + File.separator + "oneway"
				+ File.separator + "sdk" + File.separator + "c" + File.separator + "c.smali");
		if (!activity.exists()) {
			System.out.println(activity.getAbsolutePath());
			new TextToDalog("警告", "Unit.smali文件不存在!");
			return;
		}
		if (!provider.exists()) {
			new TextToDalog("警告", "c.smali文件不存在!");
			return;
		}

		/*updateActivity(activity.getAbsolutePath());
		updateProvider(provider.getAbsolutePath());*/
		config();
		SmaliUtils smali = new SmaliUtils();
		smali.setPath(path);
		smali.bale(path, path+File.separator+"new_"+core.getName());
		System.out.println(path+File.separator+"new_"+core.getName());

	}
	private void config(){
		JSONArray pluginsManual=config.getJSONArray("array").getJSONObject(2).getJSONArray("pluginsManual");
		for (Object o : pluginsManual) {
			changeSmali((JSONObject) o);
		}
	}
	private String getPackageName(){
		if(packageName!=null){
			return packageName;
		}
		JSONArray array=config.getJSONArray("array").getJSONObject(2).getJSONArray("random");
		packageName="";
		for (Object o : array) {
			packageName+=o+".";
		}
		packageName=packageName.substring(0,packageName.length()-1);
		return packageName;
	}
	private void changeSmali(JSONObject json){
		File smali=new File(home+File.separator+"smali"+File.separator+json.getString("class").replace(".",File.separator)+".smali");
		if(!smali.exists()){
			System.err.println("smali文件不存在 :"+json.getString("class"));
			return;
		}
		try {
			BufferedReader reader=new BufferedReader(new FileReader(smali));
			String tmp,str="";
			boolean find = false;
			boolean end = false;
			boolean write = false;
			while ((tmp=reader.readLine())!=null){
				if(tmp.contains(json.getString("find"))){
					System.out.println("yes!");
					find=true;
				}
				if(find&&!write){
					tmp=json.getString("data");
					tmp=tmp.replace("${packagename}",getPackageName());
					System.out.println(tmp);
					str+=tmp;
					write=true;
				}
				if(find&&tmp.contains(json.getString("end"))){
					end = true;
					find = false;
				}
				if (!find) {
					str+=tmp+"\n";
					if (end) {
						end = false;
						write = false;
					}
				}
			}
			reader.close();
			FileWriter writer=new FileWriter(smali);
			writer.write(str);
			writer.flush();
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	private void updateActivity(String path) {
		try {
			File file = new File(path);
			BufferedReader reader = new BufferedReader(new FileReader(file));

			String tmp, str = "";
			boolean write = false;
			while ((tmp = reader.readLine()) != null) {
				if (tmp.trim().equals("const-string v0, \"mobi.oneway.export.AdShowActivity\"")) {
					tmp = "    const-string v0, \"com.qy.AdShowActivity\"";
					write = true;
				}
				str += tmp + "\n";
			}
			reader.close();
			if (write) {
				FileWriter writer = new FileWriter(file);
				writer.write(str);
				writer.flush();
				writer.close();
				return;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			new TextToDalog("错误", "处理unit.smali文件失败：" + e.getMessage());
			return;
		}
		new TextToDalog("警告", "Unit.smali文件没有包含指定代码，请手动检查");
	}

	private void updateProvider(String path) {
		try {
			List<String> list = new ArrayList<>();
			File file = new File(path);
			BufferedReader reader = new BufferedReader(new FileReader(file));

			String tmp, str = "";
			boolean write = false;
			int index = 0;
			while ((tmp = reader.readLine()) != null) {
				list.add(tmp);
				if (tmp.trim().equals("const-string v1, \"mobi.oneway.export.OWProvider\"")) {
					if (list.get(index - 1).trim().equals(":try_start_0")
							&& list.get(index - 3).trim().equals("const/4 v0, 0x0")) {
						list.set(index - 3, "    const/4 v0, 0x1");
						write = true;
					}
				}
				index++;
			}
			for (String string : list) {
				str += string + "\n";
			}
			reader.close();

			if (write) {
				FileWriter writer = new FileWriter(file);
				writer.write(str);
				writer.flush();
				writer.close();
				return;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			new TextToDalog("错误", "处理c.smali文件失败：" + e.getMessage());
			return;
		}
		new TextToDalog("警告", "c.smali文件没有包含指定代码，请手动检查");
	}
}
