package com.tomastc.bta500;

import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.tomastc.bta500.lib.Settings;
import com.tomastc.bta500.lib.common.AsyncFtpClient;
import com.tomastc.bta500.lib.common.AsyncHttpClient;
import com.tomastc.bta500.lib.common.FileUtil;
import com.tomastc.bta500.lib.common.MyAlertDialog;
import com.tomastc.bta500.lib.db.DBHelper;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class SettingsActivity extends AppCompatActivity {

    private Button btn_settings_submit, btn_settings_cancel, btn_restore_default_factory;

    private String server_mode = "FTP";

    public static Map<Integer, String> prop_map = new HashMap<>();
    public static final Map<Integer, String> prop_key = new HashMap<Integer, String>() {{
        put(R.id.txt_settings_device_no, "device_no");
        put(R.id.txt_server_mode, "server_mode");
        put(R.id.txt_server, "server");
        put(R.id.txt_user, "user");
        put(R.id.txt_password, "password");
        put(R.id.txt_path, "path");
    }};

    private void init() {
         prop_map = new HashMap<Integer, String>() {{
             put(R.id.txt_settings_device_no, Settings.getDeviceNo());
             put(R.id.txt_server_mode, Settings.getServerMode());
             put(R.id.txt_server, Settings.getServer());
             put(R.id.txt_user, Settings.getUser());
             put(R.id.txt_password, Settings.getPassword());
             put(R.id.txt_path, Settings.getPath());
        }};
        // load settings
        Iterator iter = prop_map.keySet().iterator();
        while (iter.hasNext()) {
            Integer key = (Integer) iter.next();
            ((EditText) findViewById((int)key)).setText(prop_map.get(key));

            Log.d(getString(R.string.tag), "prop key:" + prop_map.get(key));
            if (key == R.id.txt_server_mode && prop_map.get(key) != null) {
                Log.d(getString(R.string.tag), "set server mode:" + prop_map.get(key));
                ((RadioButton)findViewById(
                        prop_map.get(key).equalsIgnoreCase("ftp")
                        ? R.id.rd_ftp : R.id.rd_http
                )).setChecked(true);
            }
        }

        //Set default SERVER_MODE to HTTP if not set
        if ( !((RadioButton)findViewById(R.id.rd_ftp)).isChecked() &&
                !((RadioButton)findViewById(R.id.rd_http)).isChecked() ) {
            ((RadioButton)findViewById(R.id.rd_http)).setChecked(true);
            server_mode = "HTTP";
            ((EditText)findViewById(R.id.txt_server_mode)).setText(server_mode);
            Log.d(getString(R.string.tag), "Set server_mode to HTTP coz the either isn't checked.");
        }
    }

    public void onServerModeClicked(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.rd_http:
                if (checked)
                    server_mode = "HTTP";
                    ((EditText)findViewById(R.id.txt_server_mode)).setText(server_mode);
                    break;
            case R.id.rd_ftp:
                if (checked)
                    server_mode = "FTP";
                    ((EditText)findViewById(R.id.txt_server_mode)).setText(server_mode);
                    break;
        }
    }

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

        init();

        // button
        btn_settings_submit = (Button) findViewById(R.id.btn_settings_submit);
        btn_settings_cancel = (Button) findViewById(R.id.btn_settings_cancel);
        btn_restore_default_factory = (Button) findViewById(R.id.btn_restore_default_factory);


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

                Map<String, String> map = Settings.getSettingList();
                Iterator iter = prop_map.keySet().iterator();
                while (iter.hasNext()) {
                    Integer key = (Integer) iter.next();
                    map.put(prop_key.get(key), ((EditText) findViewById((int)key)).getText().toString());
                }
                Settings.updateSettingsFile(map, getApplicationContext().getFilesDir().getAbsolutePath());

                if (Settings.getUsrList().isEmpty() || Settings.getMgmtList().isEmpty()) {
                    Toast.makeText(getBaseContext(), "Please wait while downloading new files...", Toast.LENGTH_LONG).show();

                    String localDir = getApplicationContext().getFilesDir().getAbsolutePath();
                    try {
                        if (((RadioButton)findViewById(R.id.rd_http)).isChecked()) {
                            new AsyncHttpClient(
                                    getApplicationContext()
                                    ,Settings.getServer() + "/" + Settings.getPath() + "/" + Settings.getManagementInfo()
                                    , ""
                            ) {
                                @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 {
                                            FileUtil.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());
                                        }
                                    }
                                }

                                @Override
                                protected void onError(Exception e) {

                                }
                            }
                                    .execute();
                        } else {
                            new AsyncFtpClient(new AsyncFtpClient.TaskListener() {
                                @Override
                                public void onFinished(String result) {
                                    // Do Something after the task has finished
                                    if (!result.equals("success"))
                                        Toast.makeText(getBaseContext(), "FTP error! " + result, Toast.LENGTH_LONG).show();
                                    else
                                        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);
                                                    }
                                                });
                                }
                            }).execute(Settings.getServer(), Settings.getUser(), Settings.getPassword(),
                                    AsyncFtpClient.ACTION.DOWNLOAD,
                                    localDir + "/" + Settings.getManagementInfo(),
                                    Settings.getSettingList().get("path") +
                                            "/" + Settings.getManagementInfo(),
                                    localDir + "/" + Settings.getUserInfo(),
                                    Settings.getSettingList().get("path") +
                                            "/" + Settings.getUserInfo());
                        }

                    } catch (Exception e) {

                    }
                } else {
                    Settings.readSettingFile(getApplicationContext().getFilesDir());
                    new MyAlertDialog(SettingsActivity.this, "Alert",
                            "Settings saved.",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    finish();
                                }
                            });
                }
            }
        });

        btn_settings_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        btn_restore_default_factory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // show confirm dialog
                new AlertDialog.Builder(SettingsActivity.this)
                        .setTitle("Restore Default Factory")
                        .setMessage("Do you really want to remove all data?")
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {

                                // truncate all table
                                //mHelper = new DBHelper(SettingsActivity.this);
                                //KbRecord.truncate(mHelper.getWritableDatabase());
                                //PdsRecord.truncate(mHelper.getWritableDatabase());

                                // remove all settings file
                                File dir = getApplicationContext().getFilesDir();
                                Settings.removeAllFile(dir);

                                new MyAlertDialog(SettingsActivity.this, "Alert",
                                        "Operation completed. Need to restart the application.",
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                finishAffinity();
                                                System.exit(0);
                                            }
                                        });


                            }})
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {

                                // truncate all table
                                //mHelper = new DBHelper(SettingsActivity.this);
                                //KbRecord.truncate(mHelper.getWritableDatabase());
                                //PdsRecord.truncate(mHelper.getWritableDatabase());

                                // remove all files except settings
                                File dir = getApplicationContext().getFilesDir();
                                Settings.removeAllFileExceptSettings(dir);

                                new MyAlertDialog(SettingsActivity.this, "Alert",
                                        "Operation completed. Need to restart the application.",
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                finishAffinity();
                                                System.exit(0);
                                            }
                                        });


                            }})
                        .setNeutralButton("Cancel", null)
                        .show();

            }
        });
    };
}
