package org.openhab.habdroid.ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import org.openhab.habdroid.R;
import org.openhab.habdroid.util.Constants;
import org.openhab.habdroid.util.Util;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import static org.openhab.habdroid.util.Util.getHostFromUrl;

public class LogActivity extends AppCompatActivity {
    private static final String TAG = LogActivity.class.getSimpleName();

    private ProgressBar mProgressBar;
    private TextView mLogTextView;
    private FloatingActionButton mFab;
    private ScrollView mScrollView;
    private LinearLayout mEmptyView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Util.setActivityTheme(this);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_log);

        Toolbar toolbar = findViewById(R.id.openhab_toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mFab = findViewById(R.id.shareFab);
        mLogTextView = findViewById(R.id.log);
        mProgressBar = findViewById(R.id.progressBar);
        mScrollView = findViewById(R.id.scrollview);
        mEmptyView = findViewById(android.R.id.empty);

        mFab.setOnClickListener(v -> {
            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT, mLogTextView.getText());
            sendIntent.setType("text/plain");
            startActivity(sendIntent);
        });

        setUiState(true, false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUiState(true, false);
        new GetLogFromAdbTask().execute(false);
    }

    private void setUiState(boolean isLoading, boolean isEmpty) {
        mProgressBar.setVisibility(isLoading && !isEmpty ? View.VISIBLE : View.GONE);
        mLogTextView.setVisibility(isLoading && !isEmpty ? View.GONE : View.VISIBLE);
        mEmptyView.setVisibility(isEmpty ? View.VISIBLE : View.GONE);
        if (isLoading || isEmpty) {
            mFab.hide();
        } else {
            mFab.show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        Log.d(TAG, "onCreateOptionsMenu()");
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.log_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Log.d(TAG, "onOptionsItemSelected()");
        switch (item.getItemId()) {
            case R.id.delete_log:
                setUiState(true, false);
                new GetLogFromAdbTask().execute(true);
                return true;
            case android.R.id.home:
                finish();
                // fallthrough
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private class GetLogFromAdbTask extends AsyncTask<Boolean, Void, String> {
        @Override
        protected String doInBackground(Boolean... clear) {
            StringBuilder logBuilder = new StringBuilder();
            String separator = System.getProperty("line.separator");
            try {
                if (clear[0]) {
                    Log.d(TAG, "Clear log");
                    Runtime.getRuntime().exec("logcat -b all -c");
                    return "";
                }
                Process process = Runtime.getRuntime().exec("logcat -b all -v threadtime -d");
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(process.getInputStream()));

                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    logBuilder.append(line);
                    logBuilder.append(separator);
                }
            } catch (Exception e) {
                Log.e(TAG, "Error reading log", e);
            }
            String log = logBuilder.toString();
            SharedPreferences sharedPreferences =
                    PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            String localUrl =
                    sharedPreferences.getString(Constants.PREFERENCE_LOCAL_URL, "");
            String remoteUrl =
                    sharedPreferences.getString(Constants.PREFERENCE_REMOTE_URL, "");
            if (!TextUtils.isEmpty(localUrl)) {
                log = log.replaceAll(getHostFromUrl(localUrl), "<openhab-local-address>");
            }
            if (!TextUtils.isEmpty(remoteUrl)) {
                log = log.replaceAll(getHostFromUrl(remoteUrl), "<openhab-remote-address>");
            }
            return log;
        }

        @Override
        protected void onPostExecute(String log) {
            mLogTextView.setText(log);
            setUiState(false, TextUtils.isEmpty(log));
            mScrollView.post(() -> mScrollView.fullScroll(View.FOCUS_DOWN));
        }
    }
}

@@ -3820,24 +3820,60 @@
 eparator%22);%0A
+            Process process = null;%0A
             
@@ -3874,24 +3874,24 @@
       try %7B%0A
-
             
@@ -4083,32 +4083,24 @@
             
-Process 
 process = Ru
@@ -4174,63 +4174,163 @@
     
-    BufferedReader bufferedReader
+%7D catch (Exception e) %7B%0A                Log.e(TAG, %22Error reading process%22, e);%0A            %7D%0A            if (process
  =
+=
  n
-ew BufferedReader(
+ull) %7B%0A                return %22%22;
 %0A   
@@ -4330,32 +4330,34 @@
 %22%22;%0A            
+%7D%0A
             new 
@@ -4347,24 +4347,56 @@
 %0A           
+ try (InputStreamReader reader =
  new InputSt
@@ -4431,19 +4431,99 @@
 tream())
-)
 ;%0A
+                    BufferedReader bufferedReader = new BufferedReader(reader)) %7B
 %0A       
@@ -4810,24 +4810,24 @@
 g log%22, e);%0A
-
             
@@ -4820,32 +4820,33 @@
 ;%0A            %7D%0A
+%0A
             Stri

Fix lgtm alerts (#1157)