package me.yoqi.wifiproxy;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import me.yoqi.wifiproxy.utils.ProxySetting;

/**
 * MainActivity
 * 
 * @author liuyuqi
 *
 */
public class MainActivity extends AppCompatActivity {

	Context mContext;
	Button btn1;
	EditText edt_host, edt_port;
	SharedPreferences sharedPreferences;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mContext = this;
		initView();
	}

	private void initView() {
		btn1 = (Button) findViewById(R.id.button1);
		edt_host = (EditText) findViewById(R.id.edt_host);
		edt_port = (EditText) findViewById(R.id.edt_port);

		// 恢复设置
		sharedPreferences = mContext.getSharedPreferences("setting", Context.MODE_PRIVATE);
		String host = sharedPreferences.getString("host", "192.168.6.100");
		String port = sharedPreferences.getString("port", "1080");
		edt_host.setText(host);
		edt_port.setText(port);

		btn1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setWifiProxy();
			}
		});
	}

	/**
	 * 设置wifi代理
	 */
	private void setWifiProxy() {

		if (btn1.getText().toString().equals("设置WIFI代理")) {
			ProxySetting.setWifiProxySettingsFor17And(mContext, edt_host.getText().toString().trim(),
					Integer.parseInt(edt_port.getText().toString().trim()), null);
			Toast.makeText(mContext, "设置成功！", Toast.LENGTH_SHORT).show();
			btn1.setText("取消WIFI代理");
		} else {
			ProxySetting.unsetWifiProxySettingsFor17And(mContext);
			btn1.setText("设置WIFI代理");
		}
		saveConfig();
	}

	/**
	 * 保存设置，下次直接点击按钮即可设置代理
	 */
	private void saveConfig() {
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putString("host", edt_host.getText().toString().trim());
		editor.putString("port", edt_port.getText().toString().trim());
		editor.commit();
	}
}
