package com.wizarpos.aidl.tester;


import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.wizarpos.utils.ByteConvert;
import com.wizarpos.utils.Logger;
import com.wizarpos.utils.ShellUtils;
import com.wizarpos.utils.StringUtils;
import com.wizarpos.utils.TextViewUtil;
import com.wizarpos.wizarviewagentassistant.aidl.IEth0MgrService;
import com.wizarpos.wizarviewagentassistant.aidl.ISystemExtApi;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;


public class MainActivity extends AbstractActivity implements OnClickListener , ServiceConnection{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn_test1 = (Button) this.findViewById(R.id.btn_test1);
        Button btn_test2 = (Button) this.findViewById(R.id.btn_test2);
        Button btn_test3 = (Button) this.findViewById(R.id.btn_test3);

        ((Button) this.findViewById(R.id.btn_test4)).setOnClickListener(this);
        ((Button) this.findViewById(R.id.btn_test5)).setOnClickListener(this);
        ((Button) this.findViewById(R.id.btn_test6)).setOnClickListener(this);
        ((Button) this.findViewById(R.id.btn_test7)).setOnClickListener(this);
        ((Button) this.findViewById(R.id.btn_test8)).setOnClickListener(this);

        log_text = (TextView) this.findViewById(R.id.text_result);
        log_text.setMovementMethod(ScrollingMovementMethod.getInstance());

        findViewById(R.id.settings).setOnClickListener(this);
        btn_test1.setOnClickListener(this);
        btn_test2.setOnClickListener(this);
        btn_test3.setOnClickListener(this);


        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == R.id.log_default) {
                    log_text.append("\t" + msg.obj + "\n");
                } else if (msg.what == R.id.log_success) {
                    String str = "\t" + msg.obj + "\n";
                    TextViewUtil.infoBlueTextView(log_text, str);
                } else if (msg.what == R.id.log_failed) {
                    String str = "\t" + msg.obj + "\n";
                    TextViewUtil.infoRedTextView(log_text, str);
                } else if (msg.what == R.id.log_clear) {
                    log_text.setText("");
                }
            }
        };
        bindSystemExtService();
        bindEth0MgrService();
        String auto_start = getIntent().getStringExtra("auto_start");
        Logger.debug("auto_start:%s", auto_start);
        if(auto_start != null && auto_start.length() > 0){
            writerInLog("auto start with : " + auto_start, R.id.log_default);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unbindService(this);
    }


    public void bindSystemExtService() {
        try {
            startConnectService(MainActivity.this,
                    "com.wizarpos.wizarviewagentassistant",
                    "com.wizarpos.wizarviewagentassistant.SystemExtApiService", this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void bindEth0MgrService() {
        try {
            startConnectService(MainActivity.this,
                    "com.wizarpos.wizarviewagentassistant",
                    "com.wizarpos.wizarviewagentassistant.Eth0MgrService", this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean change = false;
    public void setLanguage(){
        try {
            boolean result = false;
            if(change){
                result = systemExtApi.setLanguage(Locale.CHINESE.getLanguage(), Locale.CHINESE.getCountry(), Locale.CHINESE.getVariant());
            }else{
                result = systemExtApi.setLanguage(Locale.ENGLISH.getLanguage(), Locale.ENGLISH.getCountry(), Locale.ENGLISH.getVariant());
            }
            change = !change;
            writerInSuccessLog("set language result : " +result);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    protected boolean startConnectService(Context mContext, String packageName, String className, ServiceConnection connection) {
        boolean isSuccess = startConnectService(mContext, new ComponentName(packageName, className), connection);
        writerInLog("bind service result : " + isSuccess, R.id.log_default);
        return isSuccess;
    }

    protected boolean startConnectService(Context context, ComponentName comp, ServiceConnection connection) {
        Intent intent = new Intent();
        intent.setPackage(comp.getPackageName());
        intent.setComponent(comp);
        boolean isSuccess = context.bindService(intent, connection, Context.BIND_AUTO_CREATE);
        comp = context.startService(intent);
        Logger.debug("bind service (%s, %s)", isSuccess, comp.getPackageName(), comp.getClassName());
        return isSuccess;
    }

    @Override
    public void onClick(View arg0) {
        int index = arg0.getId();
        if (index == R.id.btn_test1) {
//            setUsrProp();//version >= 2.10.50
//            setStatusBarLocked(true);
//            blockPowerKey();
            enableMtp();
        } else if (index == R.id.btn_test2) {
            enableEth0();
//            checkBlockPowerKeyStatus();
        } else if (index == R.id.btn_test3) {
            setLanguage();
        } else if (index == R.id.btn_test4) {
        } else if (index == R.id.btn_test5) {
        } else if (index == R.id.btn_test6) {
        } else if (index == R.id.btn_test7) {
        } else if (index == R.id.btn_test8) {
        } else if (index == R.id.settings) {
            log_text.setText("");
        }
    }

    private boolean enableBlocked = true;
    private void blockPowerKey(){
        try {
            systemExtApi.setPowerKeyBlocked(enableBlocked);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
    private void checkBlockPowerKeyStatus(){
        try {
            boolean blocked = systemExtApi.isPowerKeyBlocked();
            writerInSuccessLog("terminal's power key " + (blocked?"has blocked!":"is not blocked."));
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void enableMtp(){
        try {
            boolean enable = systemExtApi.getMtpStatus();
            writerInSuccessLog("getMtpStatus  " + (enable?" enable!":"disable!"));
            systemExtApi.enableMtp(!enable);
            writerInSuccessLog("enableMtp  " + !enable);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
    private void enableEth0(){
        boolean enable = false;
        try {
            enable = eth0MgrService.getEthernetStatus();
            writerInSuccessLog("getEthernetStatus  " + (enable?" enable!":"disable!"));
            eth0MgrService.enableEthernet(!enable);
            writerInSuccessLog("enableEthernet  " + !enable);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    private void test2(){
        Map<String, String>  map =getPersistWpProperties();
        writerInSuccessLog("size: " + map.size());
        if(map.size() > 0){
            for (String key : map.keySet()){
                writerInSuccessLog(key + " = " + map.get(key));
            }
        }
    }
    public Map<String, String> getPersistWpProperties() {
        Map<String, String> propMap = new HashMap<>();
        try {
            ShellUtils.CommandResult result = ShellUtils.execCommand("getprop | grep persist.wp.usr\\\\.", false);
            String lineSeparator = System.getProperty("line.separator", "\n");
            String[] successMsg = result.successMsg.split(lineSeparator);
            Logger.debug("result.successMsg(%s): %s", ByteConvert.bytesToHexString(lineSeparator.getBytes()), successMsg.length);
            for (String str : successMsg) {
                String[] split = str.split(":");
                if (StringUtils.isBlank(split[0])) {
                    continue;
                }
                String key = split[0].replace("[", "").replace("]", "").trim();
                String value = "";
                if (split != null && split.length >= 2) {
                    value = split[1].replace("[", "").replace("]", "").trim();
                }
                propMap.put(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return propMap;
    }


    private ISystemExtApi systemExtApi;
    private IEth0MgrService eth0MgrService;

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        try {
            String des = service.getInterfaceDescriptor();
            if(des.contains("ISystemExtApi")){
                systemExtApi = ISystemExtApi.Stub.asInterface(service);
            }else if(des.contains("IEth0MgrService")){
                eth0MgrService = IEth0MgrService.Stub.asInterface(service);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }

}
