package tw.darkk6.xposed.motweaker;

import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XSharedPreferences;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;

public class MoTweaker implements IXposedHookLoadPackage, IXposedHookZygoteInit {

	private static String MyPkgName=MoTweaker.class.getPackage().getName();
	private static XSharedPreferences prefs;
	private XC_MethodHook mCBStringStartsWith,mCBGetContentWithSign;
	
	@Override
	public void initZygote(StartupParam startupParam) throws Throwable {
		if(prefs==null) prefs=new XSharedPreferences(MyPkgName, "prefs");
		else prefs.reload();
	}

	@Override
	public void handleLoadPackage(LoadPackageParam lpkg) throws Throwable {
		if(!"mong.moptt".equals(lpkg.packageName)) return;
		try{
			initCallBack(lpkg);
			XposedHelpers.findAndHookMethod("mong.moptt.ptt.EditingPost", lpkg.classLoader, "getContentWithSignature", mCBGetContentWithSign);
			XposedHelpers.findAndHookMethod("java.lang.String", lpkg.classLoader, "startsWith",String.class, mCBStringStartsWith);
			XposedBridge.log("MoPTT hook done");
		}catch(Exception e){
			XposedBridge.log("MoTweaker Err:"+e.getMessage());
		}
	}
	
	private void initCallBack(final LoadPackageParam lpkg){
		mCBGetContentWithSign=new XC_MethodHook(){
			@Override
			protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
				//先判斷設定是否啟用自訂簽名檔
				prefs.reload();
				if(prefs.getBoolean("customSign", true)){
					//如果啟用自訂簽名檔，則取得自訂的簽名檔內容
					String sign=prefs.getString("signature", "Sent from my Android");
					if(sign.length()==0) sign="Sent from my Android";
					StringBuilder result=new StringBuilder();
					/*
					 * 原本的 method 傳回 this._contentString + "\r\n\r\n--\r\n" + this.Signature;
					 * 這邊要修改的是最後面的 this.Signature
					 */
					result.append(XposedHelpers.getObjectField(param.thisObject, "_contentString"));
					result.append("\r\n\r\n--\r\n");
					result.append(sign);
					param.setResult(result.toString());
				}
			}
		};
		
		mCBStringStartsWith=new XC_MethodHook() {
			@Override
			protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
				//如果傳入參數是 "Sent from JPTT on" 且有啟用功能就 return false , 否則不影響程式運作
				if("Sent from JPTT on".equals(param.args[0])){
					//判斷設定是否啟用
					prefs.reload();
					if(prefs.getBoolean("stopTextFilter", true)){
						param.setResult(Boolean.FALSE);
					}
				}
			}
		};
	}

}
