/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 22-07-2013, Gigaset Communications GmbH
 * Feature added to configure proxy info
 */


package com.maxwell.settings.ethernet;

import java.util.List;

import com.android.settings.R;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.NetworkInfo;
import com.maxwell.net.ethernet.EthernetManager;
import com.maxwell.net.ethernet.EthernetDevInfo;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.os.SystemProperties;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.util.Slog;
import java.util.regex.*;
import android.widget.Toast;
import android.app.admin.DevicePolicyManager;
import android.content.ContentResolver;
import android.widget.AdapterView;
import android.net.ConnectivityManager;
import android.net.Proxy;
import android.net.ProxyProperties;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import java.net.InetSocketAddress;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.app.Dialog;
import android.view.View.OnClickListener;

public class ProxyConfigDialog {
    private static final String TAG = "ProxyConfigDialog";
    private static final boolean localLogV = false;

    private EditText    mHostnameField;
    private EditText    mPortField;
    private Button      mOKButton;
    private Button      mProxyButton;
    private Context mContext = null;
    private Dialog mDialog = null;

    // Matches blank input, ips, and domain names
    private static final String HOSTNAME_REGEXP =
            "^$|^[a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*(\\.[a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*)*$";
    private static final Pattern HOSTNAME_PATTERN;
    private static final String EXCLUSION_REGEXP =
            "$|^[a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*(\\.[a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*)*$";
    private static final Pattern EXCLUSION_PATTERN;
    static {
        HOSTNAME_PATTERN = Pattern.compile(HOSTNAME_REGEXP);
        EXCLUSION_PATTERN = Pattern.compile(EXCLUSION_REGEXP);
    }

    public ProxyConfigDialog(Context context) {
        mContext = context;
    }

    /*Construct Dialog for showing Proxy Configuration*/
    public Dialog buildDialogContent(Context context) {
        mDialog = new Dialog(context);
        mDialog.setTitle(R.string.proxy_config_title);
        mDialog.setCancelable(true);
        mDialog.setContentView(R.layout.proxy_configure);
	initView(mDialog);
	populateFields();
        return mDialog;
    }

    private void initView(Dialog view) {
        mHostnameField = (EditText)view.findViewById(R.id.hostname);

        mPortField = (EditText)view.findViewById(R.id.port);

        mOKButton = (Button)view.findViewById(R.id.action);
        mOKButton.setOnClickListener(mOKHandler);

        mProxyButton = (Button)view.findViewById(R.id.proxyView);
        mProxyButton.setOnClickListener(mProxyHandler);
    }

    /*Done Button Handler*/
    OnClickListener mOKHandler = new OnClickListener() {
        public void onClick(View v) {
            if (saveToDb()) {
                mHostnameField.clearFocus();
                mPortField.clearFocus();
                Toast.makeText(mContext, mContext.getResources().getString(R.string.PROXY_CONF_SUCCESS), Toast.LENGTH_LONG).show();
                mDialog.dismiss();
            }
        }
    };

    /*Proxy Button Handler*/
    OnClickListener mProxyHandler = new OnClickListener() {
        public void onClick(View v) {
            Button temp = (Button)v;
            if(temp.getText().toString().equals(mContext.getResources().getString(R.string.proxy_enable))){
	        temp.setText(mContext.getResources().getString(R.string.proxy_disable));
		mHostnameField.setEnabled(true);
		mPortField.setEnabled(true);
		mOKButton.setEnabled(true);
		mHostnameField.requestFocus();
		setProxyEnable(1);
	    } else {
		temp.setText(mContext.getResources().getString(R.string.proxy_enable));
		mHostnameField.setEnabled(false);
		mPortField.setEnabled(false);
		mOKButton.setEnabled(false);
		setProxyEnable(0);
		ProxyProperties p = new ProxyProperties("", -1, "");
		ConnectivityManager cm =
			(ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		cm.setGlobalProxy(p);
                mDialog.dismiss();
	    }
        }
    };

    void populateFields() {
        String hostname = "";
        int port = -1;

	// Use the last setting given by the user
        ConnectivityManager cm =
                (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);

        ProxyProperties proxy = cm.getGlobalProxy();
        if (proxy != null) {
            hostname = proxy.getHost();
            port = proxy.getPort();
        }

        if (hostname == null || hostname.equals("")) {
            hostname = "";
            setProxyEnable(0);
        } else {
            setProxyEnable(1);
        }

        int proxyEnable = getProxyEnable();

        if(proxyEnable == 0) {
            mHostnameField.setEnabled(false);
	    mPortField.setEnabled(false);
	    mOKButton.setEnabled(false);
            mProxyButton.setText(mContext.getResources().getString(R.string.proxy_enable));
        } else if(proxyEnable == 1) {
            mProxyButton.setText(mContext.getResources().getString(R.string.proxy_disable));
            mHostnameField.setEnabled(true);
	    mPortField.setEnabled(true);
	    mOKButton.setEnabled(true);

	    mHostnameField.setText(hostname);

	    String portStr = port == -1 ? "" : Integer.toString(port);
	    mPortField.setText(portStr);
        }
    }

    /**
     * validate syntax of hostname and port entries
     * @return 0 on success, string resource ID on failure
     */
    public static int validate(String hostname, String port) {
        Matcher match = HOSTNAME_PATTERN.matcher(hostname);

        if (!match.matches()) return R.string.proxy_error_invalid_host;

        if (hostname.length() > 0 && port.length() == 0) {
            return R.string.proxy_error_empty_port;
        }

        if (port.length() > 0) {
            if (hostname.length() == 0) {
                return R.string.proxy_error_empty_host_set_port;
            }
            int portVal = -1;
            try {
                portVal = Integer.parseInt(port);
            } catch (NumberFormatException ex) {
                return R.string.proxy_error_invalid_port;
            }
            if (portVal <= 0 || portVal > 0xFFFF) {
                return R.string.proxy_error_invalid_port;
            }
        }
        return 0;
    }

    /**
     * returns true on success, false if the user must correct something
     */
    boolean saveToDb() {

        String hostname = mHostnameField.getText().toString().trim();
        String portStr = mPortField.getText().toString().trim();
        int port = 0;

        int result = validate(hostname, portStr);
        if (result > 0) {
	    String msg = mContext.getString(validate(hostname, portStr));
	    Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
            return false;
        }

        if (portStr.length() > 0) {
            try {
                port = Integer.parseInt(portStr);
            } catch (NumberFormatException ex) {
                // should never happen - caught by validate above
                return false;
            }
        }
        ProxyProperties p = new ProxyProperties(hostname, port, "");
        ConnectivityManager cm =
                (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);

        cm.setGlobalProxy(p);

        return true;
    }

    public void setProxyEnable(int setProxy){
        final ContentResolver cr = mContext.getContentResolver();
        Settings.Secure.putInt(cr, Settings.Secure.PROXY_ENABLE, setProxy);
    }

    public int getProxyEnable() {
        final ContentResolver cr = mContext.getContentResolver();
        try {
            return Settings.Secure.getInt(cr, Settings.Secure.PROXY_ENABLE);
        } catch(SettingNotFoundException e) {
            return -1;
        }
    }
}
