package org.keyscience.app;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.widget.ImageView;
import android.widget.TextView;

import org.keyscience.BackgroundTask.HttpDrawableAsync;
import org.keyscience.BackgroundTask.URLImageParser;
import org.keyscience.R;

import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;

public class EventsActivity extends AppCompatActivity {
    private HttpDrawableAsync httpDrawableAsync;

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

        ImageView imageView = findViewById(R.id.events_activity_image);
        TextView title = findViewById(R.id.events_activity_title);
        final TextView content = findViewById(R.id.events_activity_content);

        final Intent intent = getIntent();

        byte[] byteArray = getIntent().getByteArrayExtra("image");

        if (byteArray != null) {
            Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
            imageView.setImageBitmap(bmp);
        }

        // Uses fromHtml now for special chars (Which are used by WP)
        title.setText(Html.fromHtml(intent.getStringExtra("title"), null, null));

        URLImageParser p = new URLImageParser(content, this);
        String html = intent.getStringExtra("content");
        Spanned htmlSpan = Html.fromHtml(html, p, null);
        content.setText(htmlSpan);
//        content.setText(Html.fromHtml(intent.getStringExtra("content"),
//                new Html.ImageGetter() {
//                    @Override
//                    public Drawable getDrawable(String source) {
//                        httpDrawableAsync = new HttpDrawableAsync(
//                                content, intent.getStringExtra("content"), getBaseContext());
//                        httpDrawableAsync.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, source);
//                        return null;
//                    }
//                }, null));

        // Gets URLs working in content
        content.setMovementMethod(LinkMovementMethod.getInstance());
    }

    @Override
    protected void onDestroy() {
        if (httpDrawableAsync != null) {
            httpDrawableAsync.cancel(true);
            try {
                //Waits if necessary to complete
                httpDrawableAsync.get();
            } catch (ExecutionException e) {
                //  ignore
            } catch (InterruptedException e) {
                //  ignore
            } catch (CancellationException e) {
                //  ignore
            }
            httpDrawableAsync = null;
        }
        super.onDestroy();
    }
}
