/*
 * 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.Bundle;
import android.os.Environment;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import android.support.design.widget.TextInputEditText;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ArrayAdapter; 
import com.oracle.iot.sample.FileManager.FileListOptions;
import java.io.File;
import java.io.FileFilter;

public class ProvisioningInformationActivity extends Activity {
    private static final String ERROR_TAG = "IOT_ERROR";
    private TextView mProvisioningInfo;
    private TextInputEditText mPasswordView;
    private ListView mFileListView;
    private String nextClassName = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if(getIntent().getBooleanExtra("EXIT", false)){
            finish();
            System.exit(0);
        }
        // If we have password run main activity
        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) {
            runNextActivity();
        }

        super.onCreate(savedInstanceState);

        String next = getIntent().getStringExtra("NEXT_INTENT");
        if (next != null && next.length() > 0) {
            getIntent().removeExtra("NEXT_INTENT"); 
            nextClassName = next;
        }

        setContentView(R.layout.activity_provisioning_information);
        mFileListView = (ListView)findViewById(R.id.filelistview);
        mProvisioningInfo = (TextView) findViewById(R.id.provisioning_info);
        Button okButton = (Button) findViewById(R.id.provision_button);
        Button cancelButton = (Button) findViewById(R.id.cancel_button);
        TextView mTitle = (TextView) findViewById(R.id.title);
        mPasswordView = (TextInputEditText) findViewById(R.id.password);

        String tasFile = pref.getString(getString(R.string.ta_file_path_orig),"");
        if (tasFile == null || tasFile.length() == 0) {
            FileListOptions opts = new FileManager.FileListOptions() {
                @Override
                public FileFilter getFilter() {
                    return new FileFilter() {
                        @Override
                        public boolean accept(File file) {
                            // Accept not hidden files
                            return file.isFile() && file.canRead()
                                    && !file.isHidden();
                            
                        }
                    };
                }
                @Override
                public boolean hasNavigation() {
                    return false;
                }
                @Override
                public boolean showTypes() {
                    return false;
                }
                @Override
                public boolean showDialog() {
                    return false;
                }
                @Override
                public boolean showCreateFileButton() {
                    return false;
                }
            };
            FileManager fm = new FileManager(null, opts);
            ArrayAdapter listAdapter = new ArrayAdapter<String>(this, R.layout.textrow, fm.getFileList());
            mFileListView.setAdapter(listAdapter);

            mFileListView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                        String fileName = (String)parent.getItemAtPosition(position);
                        SharedPreferences pref = getApplicationContext().getSharedPreferences(
                            getString(R.string.preference_file_key), Context.MODE_PRIVATE);
                        SharedPreferences.Editor prefsEditor = pref.edit();
                        prefsEditor.putString(getString(R.string.ta_file_path), Environment.getExternalStorageDirectory() + "/" + fileName);
                        prefsEditor.putString(getString(R.string.ta_file_path_orig), Environment.getExternalStorageDirectory() + "/" + fileName);
                        prefsEditor.putBoolean(getString(R.string.use_provided_bks), false);
                        // Remove password because it is new file
                        prefsEditor.apply();
                        showInfo();
                    }
                });
            mFileListView.setVisibility(View.VISIBLE);
            cancelButton.setVisibility(View.VISIBLE);
            mProvisioningInfo.setVisibility(View.VISIBLE);
            mTitle.setText(R.string.prompt_tas_file);
        } else {
            mFileListView.setVisibility(View.GONE);
            cancelButton.setVisibility(View.GONE);
            mProvisioningInfo.setVisibility(View.VISIBLE);
            mTitle.setText(R.string.prompt_password);
        }


        showInfo();
        //OK Button
        okButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPasswordView.setError(null);
                // Verify password
                String password = mPasswordView.getText().toString();
                // Check for a valid sharedSecret, if the user entered one.
                if (TextUtils.isEmpty(password)) {
                    mPasswordView.setError(getString(R.string.error_field_required));
                    mPasswordView.requestFocus();
                    return;
                } else {
                    SharedPreferences pref = getApplicationContext().getSharedPreferences(
                        getString(R.string.preference_file_key), Context.MODE_PRIVATE);
                    SharedPreferences.Editor prefsEditor = pref.edit();
                    prefsEditor.putString(getString(R.string.ta_password), password);
                    prefsEditor.apply();
                }
                runNextActivity();
            }
        });
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
    }

    private void runNextActivity() {
        Class<?> nextActivity = null;
        Exception e = null;
        try {
            nextActivity = Class.forName("com.oracle.iot.sample." + nextClassName);
        } catch (ClassNotFoundException ex1) {
            try {
                nextActivity = Class.forName("com.oracle.iot.sample.ext." + nextClassName);
            } catch (ClassNotFoundException ex2) {
                try {
                    nextActivity = Class.forName("com.oracle.iot.sample.enterpriseclientsample." + nextClassName);
                } catch (ClassNotFoundException ex3) {
                    e = ex3;
                }
            }
        }
        if (e == null) {
            Intent anIntent = new Intent(ProvisioningInformationActivity.this, nextActivity);
            startActivity(anIntent);
            finish();
        } else {
            Log.d(ERROR_TAG, nextClassName + " was not found");
        }
    }

    private void showInfo() {
        SharedPreferences mSharedPref = getApplicationContext().getSharedPreferences(
                getString(R.string.preference_file_key), Context.MODE_PRIVATE);
        String tas = mSharedPref.getString(getString(R.string.ta_file_path_orig),"");
        String info = null;
        if (!tas.equals("")) {
            info = "File:" + tas.substring(tas.lastIndexOf('/')) + "<br>";
        } else {
            info = "";
        }
        try {
            try (FileInputStream is = new FileInputStream(tas)) {
                Scanner sc = new Scanner(is);
                while (sc.hasNext()) {
                    String cur = sc.nextLine();
                    if (cur.startsWith("#")) {
                        info = info + cur.substring(1) + "<br>";
                    }
                }
                sc.close();
            }
        } catch (FileNotFoundException ex) {
            Log.d(ERROR_TAG, "Selected file not found");
        } catch (IOException ex) {
            Log.d(ERROR_TAG, "Can not safe to internal storage");
        }
        mProvisioningInfo.setText(Html.fromHtml(info));
    }

    private boolean isInFocus = false;

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        isInFocus = hasFocus;
    }

    @Override
    public void onPause() {
        super.onPause();
        if (!isInFocus && !isFinishing()) finish();
    }

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

    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_file_path_orig));
        prefsEditor.remove(getString(R.string.use_provided_bks));
        prefsEditor.remove(getString(R.string.ta_password));
        prefsEditor.apply();
    }
}
