package org.keyscience.adapters;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import org.keyscience.R;
import org.keyscience.app.EventsActivity;
import org.keyscience.models.EventsNewsModel;

import java.io.ByteArrayOutputStream;
import java.text.DateFormatSymbols;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

public class EventsAdapter extends RecyclerView.Adapter<EventsAdapter.EventsViewHolder> {

    private List<EventsNewsModel> mData;
    private Context context;

    public EventsAdapter(List<EventsNewsModel> mData, Context context) {
        this.mData = mData;
        this.context = context;
    }


    @NonNull
    @Override
    public EventsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, final int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.events_item, viewGroup, false);
        return new EventsViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull EventsViewHolder eventsViewHolder, int i) {
        eventsViewHolder.setData(mData.get(i));
        eventsViewHolder.setListeners();
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    class EventsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        CardView cardView;
        ImageView imageView;
        TextView title;
        TextView dateMonth;
        TextView dateDay;
        TextView eventCategories;
        String content;
        Bitmap bitmap;

        public EventsViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.events_image);
            eventCategories = itemView.findViewById(R.id.events_categories);
            title = itemView.findViewById(R.id.events_title);
            dateMonth = itemView.findViewById(R.id.events_Month);
            dateDay = itemView.findViewById(R.id.events_Day);
            cardView = itemView.findViewById(R.id.events_cardview);
        }

        public void setData(final EventsNewsModel model) {
            String strDay;
            String strMonth;

            if ( model.getImage() == null )
                imageView.setImageResource(R.drawable.stony_coral_id_lecture);
            else
                imageView.setImageBitmap(model.getImage());

            ZonedDateTime zonedDateTime;
            String stringDate = "";
            try {
                // appending of ( +01:00[Europe/Paris] ) it's just so that time can be parsed in without throwing exception since
                // the string most be such as 2007-12-03T10:15:30+01:00[Europe/Paris]. The string coming form DB is (  2007-12-03 10:15:30  )
                // It does not affect the actual date nor has any visible functionality
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    zonedDateTime = ZonedDateTime.parse(model.getDate().replace(" ", "T") + "+01:00[Europe/Paris]");

                    DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM\nd");
                    stringDate = zonedDateTime.format(format);
                }
            } catch (Exception exc) {
                exc.printStackTrace();
            }

            // Uses fromHtml now for special chars (Which are used by WP)
            title.setText(Html.fromHtml(model.getTitle().toUpperCase(),null,null));

            strMonth = dateMonthFormat(model);
            strDay = dateDayFormat(model);
            dateMonth.setText(strMonth);
            dateDay.setText(strDay);
            eventCategories.setText(model.getCategories().toUpperCase());
            content = model.getContent();
            bitmap = model.getImage();
        }

        public String dateMonthFormat(final EventsNewsModel model) {
            String date = model.getDate();
            date = date.replace("-", "");

            int iMonth = Integer.parseInt(date.substring(4,6));
            String dateMonth = (getMonth(iMonth).toUpperCase()).substring(0,3);

            return dateMonth;
        }

        public String dateDayFormat(final EventsNewsModel model) {
            String date = model.getDate();
            date = date.replace("-", "");

            String dateDay = date.substring(6,8);

            return dateDay;
        }

        public String getMonth(int month) {
            return new DateFormatSymbols().getMonths()[month-1];
        }

        public void setListeners() {
            cardView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            Intent intent = new Intent(context, EventsActivity.class);
            intent.putExtra("title", title.getText().toString());
            intent.putExtra("content", content);
            if (bitmap != null) {
                // Resizing the resolution of larger images before converting the bitmap to byte
                // array prevents crashing on older devices at time of conversion
                Bitmap lowres_bitmap = bitmap;
                if ( bitmap.getWidth() > 380 ) {
                    int width = 380;
                    int height = (bitmap.getHeight() * width / bitmap.getWidth());
                    lowres_bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
                }

                //convert bitmap to byte array
                ByteArrayOutputStream stream = new ByteArrayOutputStream();

                // Images are either JPEG or PNG formats. I noticed PNG causes a crash for JPG
                try {
                    lowres_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                } catch (Exception o) {
                    lowres_bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                }
                byte[] byteArray = stream.toByteArray();
                intent.putExtra("image", byteArray);
            }
            context.startActivity(intent);
        }

    }
}


