package com.tomastc.smartwatchclient;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.tomastc.smartwatchclient.lib.Settings;
import com.tomastc.smartwatchclient.lib.SimpleSpinObject;
import com.tomastc.smartwatchclient.lib.common.AsyncGetSpinner;
import com.tomastc.smartwatchclient.lib.common.AsyncHttpClient;
import com.tomastc.smartwatchclient.lib.common.FileUtil;
import com.tomastc.smartwatchclient.lib.common.MyAlertDialog;

import java.io.IOException;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;


public class SettingsActivity extends Activity {

    private Button btn_settings_yes, btn_settings_no;
    private TextView txt_sw_version;
    private Spinner ddl_preset;
    private DeviceInfoDisplay infoDisplay;
    private String MAC_ADDRESS = "";
    private Long DEC_MAC_ADDRESS;
    private void init() {

        SimpleSpinObject def_obj = new SimpleSpinObject("All", "All");
        new AsyncGetSpinner() {
            @Override
            public void onActionSuccess(String successMessage) {

            }

            @Override
            public void onActionFailure(Throwable throwableError) {

            }
        }.getSpinObject(getApplicationContext(), getString(R.string.web_api) + "/smw_preset_master.php",
                ddl_preset, null,
                "{\"cmd\":\"search-preset\"," +
                        "\"mac_address\":\""+DEC_MAC_ADDRESS+"\"}");
    }

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

        // update info bar
        infoDisplay = new DeviceInfoDisplay(getApplicationContext(), this);
        this.registerReceiver(this.infoDisplay, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

        btn_settings_yes = (Button)findViewById(R.id.btn_settings_yes);
        btn_settings_no = (Button)findViewById(R.id.btn_settings_no);
        txt_sw_version = (TextView)findViewById(R.id.txt_sw_version);
        ddl_preset = (Spinner)findViewById(R.id.ddl_preset);

        txt_sw_version.setText("v." + BuildConfig.VERSION_NAME);

        // Event
        btn_settings_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                new AsyncHttpClient(
                        getApplicationContext()
                        ,getString(R.string.web_api) + "/smw_preset_master.php"
                        , "{\"cmd\":\"search-preset-detail\",\"id\":\""
                        + ((SimpleSpinObject) ddl_preset.getSelectedItem()).getId()  + "\"}"
                ) {
                    @Override
                    public void onFinished(String response, int resp_code) {
                        Log.d(getString(R.string.tag), String.format("response %d:\n%s", resp_code, response));
                        if (resp_code != 200) {
                            Toast.makeText(getBaseContext(), "HTTP connection error! ", Toast.LENGTH_LONG).show();
                        } else {
                            Log.d(getString(R.string.tag), "write settings file...");
                            try {
                                (new FileUtil(getApplicationContext())).writeFile(Settings.getManagementInfo(),
                                        getApplicationContext().getFilesDir().getAbsolutePath(), response);

                                new MyAlertDialog(SettingsActivity.this, "Alert",
                                        "Operation completed. Restart the application to applied changes.",
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                finishAffinity();
                                                System.exit(0);
                                            }
                                        });
                            } catch (IOException ioe) {
                                Log.d(getString(R.string.tag), "cannot write file, error:" + ioe.getMessage());
                            }

                        }
                    }
                }
                        .execute();
            }
        });


        btn_settings_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        MAC_ADDRESS = getMacAddress();
        MAC_ADDRESS = MAC_ADDRESS.replace(":","");
        DEC_MAC_ADDRESS = Long.parseLong(MAC_ADDRESS,16);

        Log.d("TESTAA",MAC_ADDRESS +"=" + DEC_MAC_ADDRESS);

        // initial
        init();
    }
    public String getMacAddress() {
        try {
            List<NetworkInterface> networkInterfaceList = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface networkInterface : networkInterfaceList) {
                if (!networkInterface.getName().equalsIgnoreCase("wlan0")) {
                    continue;
                }

                byte[] macAddress = networkInterface.getHardwareAddress();
                if (macAddress == null) {
                    return "";
                }

                StringBuilder result = new StringBuilder();
                for (byte data : macAddress) {
                    Log.d("TESTAA"," data =" + data);
                    String test = String.valueOf(Integer.toHexString(data & 0xFF));
                    test = String.format("%2s",test).replace(' ','0');
                    result.append(test).append(":");
                    Log.d("TESTAA"," result =" + result);
                }

                if (result.length() > 0) {
                    result.deleteCharAt(result.length() - 1);
                }
                return result.toString();
            }
        } catch (Exception ignored) {
        }
        return "02:00:00:00:00:00";
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (this.infoDisplay != null) {
            this.unregisterReceiver(this.infoDisplay);
        }
    }
}