package com.wabadaba.prefsedit;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v13.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.wabadaba.prefsedit.adapter.AppItem;

import java.util.List;

import eu.davidea.flexibleadapter.FlexibleAdapter;
import java8.util.stream.Collectors;
import java8.util.stream.StreamSupport;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private PackageManager pm;
    private FlexibleAdapter<AppItem> adapter;
    private MaterialDialog loadingDialog;

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

        pm = getPackageManager();

        checkPermissions();

        new LoadAppsTask().execute();

//        Serializer serializer = new Persister();
//        PrefMap prefMap = new PrefMap(
//                Lists.newArrayList(new BooleanPref("b1", true)),
//                Lists.newArrayList(new IntPref("i1", 32)),
//                Lists.newArrayList(new LongPref("l1", 64)),
//                Lists.newArrayList(new StringPref("s1", "s1v"), new StringPref("s2", "s2v")));
//        File file = new File(getFilesDir() + "/test.xml");
//        try {
//            serializer.write(prefMap, file);
//
//            FileInputStream fileIS = new FileInputStream(file);
//            BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
//
//            String readString;
//            //just reading each line and pass it on the debugger
//            while ((readString = buf.readLine()) != null) {
//                Utils.log(readString);
//
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    private class LoadAppsTask extends AsyncTask<Void, Void, List<AppItem>> {

        @Override
        protected List<AppItem> doInBackground(Void... params) {
            return StreamSupport.stream(getAppList())
                    .map(AppItem::new)
                    .collect(Collectors.toList());
        }

        @Override
        protected void onPreExecute() {
            loadingDialog = new MaterialDialog.Builder(MainActivity.this)
                    .title(R.string.loading_apps)
                    .content(R.string.please_wait)
                    .progress(true, 0)
                    .autoDismiss(false)
                    .build();
            loadingDialog.show();
        }

        @Override
        protected void onPostExecute(List<AppItem> appItems) {
            RecyclerView appListView = (RecyclerView) findViewById(R.id.app_list);
            adapter = new FlexibleAdapter<>(appItems, (FlexibleAdapter.OnItemClickListener) MainActivity.this::showDetailsActivity);
            appListView.setLayoutManager(new LinearLayoutManager(getParent()));
            appListView.setAdapter(adapter);
            loadingDialog.dismiss();
        }
    }

    @SuppressWarnings("SameReturnValue")
    private boolean showDetailsActivity(int position) {
        AppItem item = adapter.getItem(position);
        AppInfo info = item.getInfo();

        Intent intent = new Intent(this, DetailsActivity.class);
        intent.putExtra("package_name", info.packageName);
        startActivity(intent);

        return true;
    }

    private List<AppInfo> getAppList() {
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        return StreamSupport.stream(pm.queryIntentActivities(mainIntent, 0))
                .sorted(new ResolveInfo.DisplayNameComparator(pm))
                .map(resolveInfo -> new AppInfo(resolveInfo, pm))
                .collect(Collectors.toList());
    }

    private void checkPermissions() {
        //Storage permission
        int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }

        //Root access
        if (Utils.isRooted()) {
            Utils.log("Device rooted");
        } else {
            Utils.logError("Device not rooted");
        }
    }
}
