package ch.threema.app.activities;

import android.app.LoaderManager;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.GridView;

import org.slf4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import ch.threema.app.R;
import ch.threema.app.adapters.StickerSelectorAdapter;
import ch.threema.app.ui.InsetSides;
import ch.threema.app.ui.SpacingValues;
import ch.threema.app.ui.ViewExtensionsKt;
import static ch.threema.base.utils.LoggingKt.getThreemaLogger;

import static ch.threema.app.utils.ActiveScreenLoggerKt.logScreenVisibility;

public class StickerSelectorActivity extends ThreemaToolbarActivity implements LoaderManager.LoaderCallbacks<String[]> {
    private static final Logger logger = getThreemaLogger("StickerSelectorActivity");

    private static final String STICKER_DIRECTORY = "emojione";
    private static final String STICKER_INDEX = STICKER_DIRECTORY + "/contents.txt";
    public static final String EXTRA_STICKER_PATH = "spath";
    private GridView gridView;
    private StickerSelectorAdapter adapter;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        logScreenVisibility(this, logger);

        gridView = findViewById(R.id.grid_view);
        gridView.setOnItemClickListener((adapterView, view, i, l) -> {
            if (adapter != null) {
                Intent intent = new Intent();
                intent.putExtra(EXTRA_STICKER_PATH, adapter.getItem(i));
                setResult(RESULT_OK, intent);
                finish();
            }
        });

        getLoaderManager().initLoader(0, null, this).forceLoad();
    }

    @Override
    protected void handleDeviceInsets() {
        ViewExtensionsKt.applyDeviceInsetsAsPadding(
            findViewById(R.id.grid_view),
            InsetSides.all(),
            SpacingValues.symmetric(R.dimen.grid_unit_x4, R.dimen.grid_unit_x1)
        );
    }

    private static class StickerLoader extends AsyncTaskLoader<String[]> {
        StickerLoader(Context context) {
            super(context);
        }

        @NonNull
        @Override
        public String[] loadInBackground() {
            // AssetManager.getAssets().list is notoriously slow on some phones, so we use a list file to get the filenames quickly
            try {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader((getContext().getAssets().open(STICKER_INDEX))))) {
                    List<String> files = new ArrayList<>();

                    String line;
                    while ((line = reader.readLine()) != null) {
                        files.add(STICKER_DIRECTORY + "/" + line);
                    }

                    return files.toArray(new String[0]);
                }
            } catch (IOException e) {
                logger.error("Exception", e);
            }
            return new String[0];
        }
    }

    @Override
    public int getLayoutResource() {
        return R.layout.activity_sticker_selector;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return false;
    }

    @Override
    public Loader<String[]> onCreateLoader(int id, Bundle args) {
        return new StickerLoader(getApplicationContext());
    }

    @Override
    public void onLoadFinished(Loader<String[]> loader, String[] data) {
        adapter = new StickerSelectorAdapter(this, data);
        gridView.setAdapter(adapter);
    }

    @Override
    public void onLoaderReset(Loader<String[]> loader) {
        gridView.setAdapter(null);
    }
}
