/*
 * Copyright (c) 2017 Oracle and/or its affiliates.  All rights reserved.
 *
 * This software is dual-licensed to you under the MIT License (MIT) and
 * the Universal Permissive License (UPL).  See the LICENSE file in the root
 * directory for license terms.  You may choose either license, or both.
 */

package com.oracle.iot.sample;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class NetworkProvisionActivity extends Activity {
    private final String ERROR_TAG = "NetworkProvisionErr";
    Activity activity;
    TextView status;
    ProgressBar statusBar;
    Button cancelButton;
    Button okButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if(getIntent().getBooleanExtra("EXIT", false)){
            finish();
            System.exit(0);
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_network_provision);
        activity = this;
        cancelButton = (Button) findViewById(R.id.cancel_button);
        okButton = (Button) findViewById(R.id.ok_button);
        status = (TextView) findViewById(R.id.status);
        statusBar = (ProgressBar) findViewById(R.id.progress_bar);

        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clearProperties();
                Bootstrapper.interruptProvisioning();
                Intent anIntent = new Intent(NetworkProvisionActivity.this, SelectProvisioningActivity.class);
                startActivity(anIntent);
                finish();
            }
        });
        
        okButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clearProperties();
                // Go to select method
                Intent anIntent = new Intent(NetworkProvisionActivity.this, SelectProvisioningActivity.class);
                startActivity(anIntent);
                finish();
            }
        });
    }

private class ProgressTask extends AsyncTask <Void,Void,Void> {
    @Override
    protected void onPreExecute() {
        statusBar.setVisibility(View.VISIBLE);
        statusBar.setIndeterminate(true);
        cancelButton.setVisibility(View.VISIBLE);
        status.setVisibility(View.GONE);
        okButton.setVisibility(View.GONE);
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        String destinationFileName = getApplicationContext().getFilesDir().getPath() + "/bootstraper.conf";
        SharedPreferences pref = getApplicationContext().getSharedPreferences(
            getString(R.string.preference_file_key), Context.MODE_PRIVATE);
        String pass = pref.getString(getString(R.string.ta_password),"");
        if (pass.length() > 0) {
            Bootstrapper.TaskResult<Boolean> result = Bootstrapper.provision(activity, destinationFileName, pass);
            if (result.getResult() != null && result.getResult().equals(Boolean.TRUE)) {
                SharedPreferences.Editor prefsEditor = pref.edit();
                prefsEditor.putString(getString(R.string.ta_file_path), destinationFileName);
                prefsEditor.putString(getString(R.string.ta_file_path_orig), destinationFileName);
                prefsEditor.putBoolean(getString(R.string.use_provided_bks), false);
                prefsEditor.apply();
                // ProvisioningInformationActivity must suddenly run MainActivity screen
                Intent anIntent = new Intent(NetworkProvisionActivity.this, ProvisioningInformationActivity.class);
                anIntent.putExtra("NEXT_INTENT", "MainActivity");
                startActivity(anIntent);
                finish();
            } else {
                if (result.getError() != null) {
                    StringBuilder sb = new StringBuilder();
                    Throwable ex = result.getError();
                    status.setText(ex.getMessage() != null ? ex.getMessage() : "Can not provision");
                    while (ex != null) {
                        if (ex.getMessage() != null) {
                            sb.append("'").append(ex.getMessage()).append("'");
                        } else {
                            sb.append("'").append(ex.getClass().getName()).append("'");
                        }
                        ex = ex.getCause();
                        if (ex != null) {
                            sb.append(" caused by ");
                        }
                    }
                    Log.d(ERROR_TAG, sb.toString());
                } else {
                    status.setText("Can not provision");
                }
                showError();
            }
        } else {
            status.setText("Password is empty");
            showError();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
    }
}
    
    private void clearProperties() {
        // Clear
        SharedPreferences pref = getApplicationContext().getSharedPreferences(
            getString(R.string.preference_file_key), Context.MODE_PRIVATE);
        SharedPreferences.Editor prefsEditor = pref.edit();
        prefsEditor.remove(getString(R.string.ta_file_path));
        prefsEditor.remove(getString(R.string.ta_password));
        prefsEditor.remove(getString(R.string.ta_file_path_orig));
        prefsEditor.remove(getString(R.string.use_provided_bks));
        prefsEditor.remove(getString(R.string.ta_password));
        prefsEditor.apply();
    }
    
    @Override
    protected void onStart() {
        super.onStart();
        Thread thr1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    new ProgressTask().execute().get(60000, TimeUnit.MILLISECONDS);
                } catch (InterruptedException | ExecutionException | TimeoutException ex) {
                    Log.d(ERROR_TAG, (ex.getMessage() == null ? ex.getClass().getName() : ex.getMessage()));
                }
            }
        });
        thr1.start();
    }
    
    void showError() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                statusBar.setVisibility(View.GONE);
                cancelButton.setVisibility(View.GONE);
                status.setVisibility(View.VISIBLE);
                okButton.setVisibility(View.VISIBLE); 
            }
        });
    }

    @Override
    public void onBackPressed() {
        clearProperties();
        // Go to select method
        Intent anIntent = new Intent(NetworkProvisionActivity.this, SelectProvisioningActivity.class);
        startActivity(anIntent);
        finish();
    }
}
