package de.sebse.fuplanner.fragments.moddetails;

import android.content.Intent;
import android.net.Uri;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.ms.square.android.expandabletextview.ExpandableTextView;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.services.kvv.types.Announcement;
import de.sebse.fuplanner.services.kvv.types.Assignment;
import de.sebse.fuplanner.services.kvv.types.Event;
import de.sebse.fuplanner.services.kvv.types.Lecturer;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.tools.UtilsDate;
import de.sebse.fuplanner.tools.logging.Logger;
import de.sebse.fuplanner.tools.ui.CustomViewHolder;
import de.sebse.fuplanner.tools.ui.ItemViewHolder;
import de.sebse.fuplanner.tools.ui.MailViewHolder;
import de.sebse.fuplanner.tools.ui.ShortcutViewHolder;
import de.sebse.fuplanner.tools.ui.StringViewHolder;

class ModDetailOverviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int MAX_ITEMS_PER_PREVIEW = 2;

    private static final int TYPE_HEADER = 0;
    private static final int TYPE_DESCRIPTION = 1;
    private static final int TYPE_ITEM = 2;
    private static final int TYPE_SHOW_MORE = 3;
    private static final int TYPE_MAIL = 4;
    private static final int TYPE_SHORTCUTS = 5;

    @Nullable private final ModDetailListener mListener;

    private Modules.Module mValue;
    private final ArrayList<Pair<Integer, Object>> mPositionalData;
    private Logger log = new Logger(this);

    ModDetailOverviewAdapter(@Nullable final ModDetailListener listener) {
        mValue = null;
        mPositionalData = new ArrayList<>();
        mListener = listener;
    }

    public void setModule(Modules.Module module) {
        mValue = module;
        this.setModule();
    }

    private void setModule() {
        mPositionalData.clear();
        mPositionalData.add(new Pair<>(TYPE_HEADER, ModulePart.DESCRIPTION));
        mPositionalData.add(new Pair<>(TYPE_DESCRIPTION, null));
        mPositionalData.add(new Pair<>(TYPE_SHORTCUTS, null));
        mPositionalData.add(new Pair<>(TYPE_HEADER, ModulePart.LECTURERS));
        for (int i = 0; i < mValue.lecturer.size(); i++) {
            mPositionalData.add(new Pair<>(TYPE_MAIL, ModulePart.LECTURERS+1024*i));
        }
        mPositionalData.add(new Pair<>(TYPE_HEADER, ModulePart.ANNOUNCEMENT));
        addPositionalListData(getAnnounceCount(), ModulePart.ANNOUNCEMENT);
        mPositionalData.add(new Pair<>(TYPE_HEADER, ModulePart.ASSIGNMENT));
        addPositionalListData(getAssignmentCount(), ModulePart.ASSIGNMENT);
        mPositionalData.add(new Pair<>(TYPE_HEADER, ModulePart.EVENT));
        addPositionalListData(getEventsCount(), ModulePart.EVENT);
        this.notifyDataSetChanged();
    }

    private void addPositionalListData(int count, int category) {
        for (int i = 0; i < Math.min(MAX_ITEMS_PER_PREVIEW, count); i++) {
            mPositionalData.add(new Pair<>(TYPE_ITEM, category+1024*i));
        }
        if (count > MAX_ITEMS_PER_PREVIEW)
            mPositionalData.add(new Pair<>(TYPE_SHOW_MORE, category));
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        switch (viewType) {
            case TYPE_HEADER:
                view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.list_all_caption, parent, false);
                return new StringViewHolder(view);
            case TYPE_DESCRIPTION:
                view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.list_moddetails_description, parent, false);
                return new DescriptionViewHolder(view);
            case TYPE_ITEM:
                view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.list_all_items, parent, false);
                return new ItemViewHolder(view);
            case TYPE_SHOW_MORE:
                view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.list_all_show_more, parent, false);
                return new CustomViewHolder(view);
            case TYPE_MAIL:
                view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.list_all_mails, parent, false);
                return new MailViewHolder(view);
            case TYPE_SHORTCUTS:
                view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.list_moddetails_shortcuts, parent, false);
                return new ShortcutViewHolder(view);
            default:
                //noinspection ConstantConditions
                return null;
        }
    }

    @Override
    public int getItemViewType(int position) {
        // Note that unlike in ListView adapters, types don't have to be contiguous
        if (position < mPositionalData.size())
            return mPositionalData.get(position).first;
        else return -1;
    }

    @Override
    public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
        if (mValue == null || position > mPositionalData.size())
            return;
        Pair<Integer, Object> data = mPositionalData.get(position);
        switch (data.first) {
            case TYPE_HEADER:
                StringViewHolder h = (StringViewHolder) holder;
                switch ((Integer) data.second) {
                    case ModulePart.DESCRIPTION:
                        h.mString.setText(R.string.description);
                        break;
                    case ModulePart.LECTURERS:
                        h.mString.setText(h.mView.getResources().getString(R.string.lecturers));
                        break;
                    case ModulePart.ANNOUNCEMENT:
                        h.mString.setText(h.mView.getResources().getString(R.string.announcements_count, getAnnounceCount()));
                        break;
                    case ModulePart.ASSIGNMENT:
                        h.mString.setText(h.mView.getResources().getString(R.string.assignments_count, getAssignmentCount()));
                        break;
                    case ModulePart.EVENT:
                        h.mString.setText(h.mView.getResources().getString(R.string.upcoming_events_count, getEventsCount()));
                        break;
                }
                break;
            case TYPE_DESCRIPTION:
                DescriptionViewHolder d = (DescriptionViewHolder) holder;
                d.mText.setText(mValue.description);
                break;
            case TYPE_ITEM:
                int section = ((Integer) data.second) % 1024;
                int index = ((Integer) data.second) / 1024;
                ItemViewHolder i = (ItemViewHolder) holder;
                switch (section) {
                    case ModulePart.ANNOUNCEMENT:
                        if (mValue.announcements == null) throw new AssertionError();
                        Announcement announce = mValue.announcements.get(index);
                        i.mTitle.setText(announce.getTitle());
                        i.mSubLeft.setText(announce.getCreatedBy());
                        i.mSubRight.setText(UtilsDate.getModifiedDateTime(i.mView.getContext(), announce.getCreatedOn()));
                        i.mView.setOnClickListener(view -> {
                            if (mListener != null) mListener.gotoFragmentPart(section, index);
                        });
                        break;
                    case ModulePart.ASSIGNMENT:
                        if (mValue.assignments == null) throw new AssertionError();
                        Assignment assignment = mValue.assignments.get(index);
                        i.mTitle.setText(assignment.getTitle());
                        if(assignment.isOpen())
                            i.mSubLeft.setText(i.mView.getResources().getText(R.string.open));
                        else
                            i.mSubLeft.setText(i.mView.getResources().getText(R.string.closed));
                        i.mSubRight.setText(UtilsDate.getModifiedDateTime(i.mView.getContext(), assignment.getDueDate()));
                        i.mView.setOnClickListener(view -> {
                            if (mListener != null) mListener.gotoFragmentPart(section, index);
                        });
                        break;
                    case ModulePart.EVENT:
                        if (mValue.events == null) throw new AssertionError();
                        Event event = mValue.events.getUpcoming(index);
                        i.mTitle.setText(event.getTitle());
                        i.mSubLeft.setText(event.getType());
                        String start, end;
                        if (UtilsDate.dateEquals(event.getStartDate(), System.currentTimeMillis()))
                            start = UtilsDate.getModifiedTime(i.mView.getContext(), event.getStartDate());
                        else
                            start = UtilsDate.getModifiedDateTime(i.mView.getContext(), event.getStartDate());
                        if (UtilsDate.dateEquals(event.getStartDate(), event.getEndDate()))
                            end = UtilsDate.getModifiedTime(i.mView.getContext(), event.getEndDate());
                        else
                            end = UtilsDate.getModifiedDateTime(i.mView.getContext(), event.getEndDate());
                        i.mSubRight.setText(i.mView.getResources().getString(R.string.date_scale,
                                start, end
                                ));
                        i.mView.setOnClickListener(view -> {
                            if (mListener != null) mListener.gotoFragmentPart(section, index);
                        });
                        break;
                }
                break;
            case TYPE_MAIL:
                section = ((Integer) data.second) % 1024;
                index = ((Integer) data.second) / 1024;
                MailViewHolder m = (MailViewHolder) holder;
                switch (section) {
                    case ModulePart.LECTURERS:
                        Lecturer lecturer = mValue.lecturer.get(index);
                        m.mTitle.setText(lecturer.getName());
                        m.mSubLeft.setText(lecturer.getMail());
                        m.mIcon.setOnClickListener(view -> {
                            String defaultText = m.mView.getResources().getString(R.string.mail_default_text,
                                    lecturer.getName());
                            Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
                            emailIntent.setData(Uri.parse("mailto:"+lecturer.getMail()));
                            emailIntent.putExtra(Intent.EXTRA_SUBJECT, mValue.title);
                            emailIntent.putExtra(Intent.EXTRA_TEXT, defaultText);
                            m.mView.getContext().startActivity(emailIntent);
                        });
                        break;
                }
                break;
            case TYPE_SHORTCUTS:
                ShortcutViewHolder s = (ShortcutViewHolder) holder;
                s.mLeft.setOnClickListener(view -> {
                    if (mListener != null) mListener.gotoFragmentPart(ModulePart.RESOURCES, -1);
                });
                s.mRight.setOnClickListener(view -> {
                    if (mListener != null) mListener.gotoFragmentPart(ModulePart.GRADEBOOK, -1);
                });
                break;
            case TYPE_SHOW_MORE:
                CustomViewHolder c = (CustomViewHolder) holder;
                c.mView.setOnClickListener(view -> {
                    if (mListener != null) mListener.gotoFragmentPart((Integer) data.second, -1);
                });
                break;
        }
    }

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

    private int getAnnounceCount() {
        if (mValue.announcements != null)
            return mValue.announcements.size();
        return 0;
    }

    private int getAssignmentCount() {
        if (mValue.assignments != null)
            return mValue.assignments.size();
        return 0;
    }

    private int getEventsCount() {
        if (mValue.events != null)
            return mValue.events.sizeUpcoming();
        return 0;
    }










    class DescriptionViewHolder extends CustomViewHolder {
        final ExpandableTextView mText;

        DescriptionViewHolder(View view) {
            super(view);
            mText = view.findViewById(R.id.expand_text_view);//.findViewById(R.id.description);
        }

        @NonNull
        @Override
        public String toString() {
            return super.toString() + " '" + mText.getText() + "'";
        }
    }


}
