/*
 * Copyright (C) 2010 The Android-x86 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.
 *
 * Author: Yi Sun <beyounn@gmail.com>
 * 22-07-2013, Gigaset Communications GmbH
 * Feature added to configure ethernet ip
 */


package com.maxwell.settings.ethernet;

import com.android.settings.R;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.wifi.WifiSettings;

import android.app.Activity;
import android.app.Dialog;
import android.app.ActionBar;
import android.view.Gravity;
import android.content.Context;
import com.maxwell.net.ethernet.EthernetManager;
import android.content.DialogInterface;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.widget.Switch;
import android.util.Log;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import android.widget.TextView;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Notification.Builder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.DetailedState;
import android.net.NetworkInfo.State;

public class EthernetSettings extends SettingsPreferenceFragment {
    private static final String LOG_TAG = "Ethernet";
    private static final boolean LOCAL_LOGD = true;
    private static final String KEY_CONF_ETH = "ETHERNET_config";
    private static final String KEY_CONF_PROXY = "PROXY_config";
    private static final String ETHSTATE_CHANGE = "com.maxwell.net.ethernet.ETHSTATE_CHANGE";
    private static final String PCWIFICLIENT_STATE = "com.maxwell.net.ethernet.PCWIFICLIENT_STATE";

    private EthernetEnabler mEthEnabler;
    private EthernetConfigDialog mEthConfigDialog;
    private ProxyConfigDialog mProxyConfigDialog;
    private EthernetManager mEthMgr;
    private Preference mEthConfigPref;
    private Preference mProxyConfigPref;
    private IntentFilter mFilter;
    private TextView mEmptyView;

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
            public void onReceive(Context context, Intent intent) {
                if(intent != null) {
                    handleEvent(context, intent);
                }
            }
    };

    @Override
        public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
            super.onPreferenceTreeClick(preferenceScreen, preference);

            if (preference == mEthConfigPref) {
                final Dialog EthConfDialog = mEthConfigDialog.buildDialogContent(getActivity());
                EthConfDialog.show();
            } else if(preference == mProxyConfigPref) {
                final Dialog ProxyDialog = mProxyConfigDialog.buildDialogContent(getActivity());
                ProxyDialog.show();
            }
            return false;
        }

    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }

    @Override
        public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            return super.onCreateView(inflater, container, savedInstanceState);
        }

    @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);

            mFilter = new IntentFilter();
            mFilter.addAction(EthernetManager.ETHERNET_STATE_CHANGED_ACTION);
            mFilter.addAction(EthernetManager.NETWORK_STATE_CHANGED_ACTION);
            mFilter.addAction(ETHSTATE_CHANGE);
            mFilter.addAction(PCWIFICLIENT_STATE);
            

            addPreferencesFromResource(R.xml.ethernet_settings);

            final Activity activity = getActivity();

            /* Creating Ethernet Switch */
            Switch actionBarSwitch = new Switch(activity);

            if (activity instanceof PreferenceActivity) {
                PreferenceActivity preferenceActivity = (PreferenceActivity) activity;
                if (preferenceActivity.onIsHidingHeaders() || !preferenceActivity.onIsMultiPane()) {
                    final int padding = activity.getResources().getDimensionPixelSize(
                            R.dimen.action_bar_switch_padding);
                    actionBarSwitch.setPadding(0, 0, padding, 0);
                    activity.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM,
                            ActionBar.DISPLAY_SHOW_CUSTOM);
                    activity.getActionBar().setCustomView(actionBarSwitch, new ActionBar.LayoutParams(
                                ActionBar.LayoutParams.WRAP_CONTENT,
                                ActionBar.LayoutParams.WRAP_CONTENT,
                                Gravity.CENTER_VERTICAL | Gravity.END));
                }
            }

            //mEthEnabler = new EthernetEnabler(activity, actionBarSwitch);
            mEthConfigDialog = new EthernetConfigDialog(activity);
            mProxyConfigDialog = new ProxyConfigDialog(activity);
            mEthMgr = (EthernetManager) getSystemService(Context.ETHERNET_SERVICE);

            final PreferenceScreen preferenceScreen = getPreferenceScreen();
            mEthConfigPref = preferenceScreen.findPreference(KEY_CONF_ETH);
            mProxyConfigPref = preferenceScreen.findPreference(KEY_CONF_PROXY);

            mEmptyView = (TextView) getView().findViewById(android.R.id.empty);
            getListView().setEmptyView(mEmptyView);

            updateEthState();

        }

    private void addMessagePreference(int messageId) {
        if (mEmptyView != null) mEmptyView.setText(messageId);
        getPreferenceScreen().removeAll();
    }

    private void setPreference(boolean enable) {
        if(LOCAL_LOGD) Log.d(LOG_TAG, "setPreference" + enable);
        mEthConfigPref.setEnabled(enable);
        mProxyConfigPref.setEnabled(enable);
    }

    @Override
        public void onResume() {
            super.onResume();
            if(mEthEnabler != null) {
                mEthEnabler.resume();
            }
			getActivity().registerReceiver(mReceiver, mFilter);
        }

    @Override
        public void onPause() {
            super.onPause();
            if(mEthEnabler != null) {
                mEthEnabler.pause();
            }
			getActivity().unregisterReceiver(mReceiver);
        }

    @Override
        public void onDestroy() {
            super.onDestroy();
            if(mEthEnabler != null) {
                mEthEnabler.destroy();
            } 
            
        }   

    private void handleEvent(Context context, Intent intent) {
        String action = intent.getAction();
        if (EthernetManager.ETHERNET_STATE_CHANGED_ACTION.equals(action)) {
        } else if (EthernetManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
        }else if(ETHSTATE_CHANGE.equals(action)) {
            updateEthState();
        }else if(PCWIFICLIENT_STATE.equals(action)) {
            boolean pCWifiClientstatus = intent.getExtras().getBoolean("PCWIFICLIENT_STATUS");
            updatePCWifClientStatus(pCWifiClientstatus);
        }
    }

    private void updateEthState() {
        if (getActivity() == null) return;

        final int EthState = mEthMgr.getState();
        final int IntState = mEthMgr.getIntState();
        if(LOCAL_LOGD) Log.d(LOG_TAG, "updateEthState" + EthState + IntState);

        switch (EthState) {
            case EthernetManager.ETHERNET_STATE_DISABLED:
                if(IntState == EthernetManager.ETHERNET_STATE_DISABLED) {
                    addMessagePreference(R.string.ethernet_empty_list_ethernet_off);
                } else if (IntState == EthernetManager.ETHERNET_STATE_DISABLING) {
                    addMessagePreference(R.string.ethernet_stopping);
                } else {
                    Log.e(LOG_TAG, "UnknownState");
                }
                break;

            case EthernetManager.ETHERNET_STATE_ENABLED:
                if(IntState == EthernetManager.ETHERNET_STATE_ENABLING) {
                    getPreferenceScreen().addPreference(mEthConfigPref);
                    getPreferenceScreen().addPreference(mProxyConfigPref);
                } else if(IntState == EthernetManager.ETHERNET_STATIC_IP_CONFIGURING) {
                    if (mEmptyView != null) mEmptyView.setText(R.string.ethernet_static_ip_configure);
                    getPreferenceScreen().removeAll();
                } else if(IntState == EthernetManager.ETHERNET_DHCP_IP_CONFIGURING) {
                    if (mEmptyView != null) mEmptyView.setText(R.string.ethernet_dhcp_ip_configure);
                    getPreferenceScreen().removeAll();
                } else if(IntState == EthernetManager.ETHERNET_IP_CONF_SUCCESS) {
                    getPreferenceScreen().removeAll();
                    getPreferenceScreen().addPreference(mEthConfigPref);
                    getPreferenceScreen().addPreference(mProxyConfigPref);
                } else if(IntState == EthernetManager.ETHERNET_STATIC_IP_ERROR) {
                    if (mEmptyView != null) mEmptyView.setText(R.string.ethernet_static_error);
                    getPreferenceScreen().addPreference(mEthConfigPref);
                    getPreferenceScreen().addPreference(mProxyConfigPref);
                } else if(IntState == EthernetManager.ETHERNET_DHCP_IP_ERROR) {
                    if (mEmptyView != null) mEmptyView.setText(R.string.ethernet_dhcp_error);
                    getPreferenceScreen().addPreference(mEthConfigPref);
                    getPreferenceScreen().addPreference(mProxyConfigPref);
                } else if(IntState == EthernetManager.ETHERNET_LINK_DOWN) {
                    if (mEmptyView != null) mEmptyView.setText(R.string.ethernet_linkdown_error);
                    getPreferenceScreen().removeAll();
                } else {
                    Log.e(LOG_TAG, "UnknownState");
                }
                break;

            case EthernetManager.ETHERNET_STATE_PCPORT_ETHERNET_ENABLED:
                addMessagePreference(R.string.wificlient_on);
                break;
        }
    }

    private void updatePCWifClientStatus(boolean isPCWifiClientStatus) {
        if (getActivity() == null) return;

        if(LOCAL_LOGD) Log.d(LOG_TAG, "updatePCWifClientStatus" + isPCWifiClientStatus);

        if(isPCWifiClientStatus) {
            addMessagePreference(R.string.wificlient_on);
        } else {
            getPreferenceScreen().addPreference(mEthConfigPref);
            getPreferenceScreen().addPreference(mProxyConfigPref);
        }
    }


}
