/*
 * DSBDirect
 * Copyright (C) 2019 Fynn Godau
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * This software is not affiliated with heinekingmedia GmbH, the
 * developer of the DSB platform.
 */

package godau.fynn.dsbdirect.table.reader;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import godau.fynn.dsbdirect.Utility;
import godau.fynn.dsbdirect.manager.ShortcodeManager;
import godau.fynn.dsbdirect.table.Entry;
import godau.fynn.dsbdirect.table.Table;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import javax.annotation.Nullable;
import java.util.*;

import static android.content.Context.MODE_PRIVATE;

public abstract class Reader {
    // Reader is just used as a synonym for Parser

    protected String mHtml;
    private ShortcodeManager shortcodeManager = null;
    /**
     * Entries are centrally managed by Reader, to which they are added with {@link #entries}, but returned in
     * each {@link #read()} method by calling {@link #getEntries()}
     */
    private ArrayList<Entry> entries = new ArrayList<>();

    public Reader(String html, @Nullable Context context) {
        mHtml = html;
        if (context != null) {
            shortcodeManager = new ShortcodeManager(context);
        }
    }

    public abstract ArrayList<Entry> read();

    /**
     * @see #entries
     */
    protected void addEntry(@Nullable String affectedClass, @Nullable String lesson, @Nullable String replacementTeacher,
                            @Nullable String info, @Nullable Date date) {

        Entry e = new Entry(affectedClass, lesson, replacementTeacher, info, date, shortcodeManager);

        // Test whether entry already exists
        for (Entry existingEntry :
                entries) {
            if (existingEntry.equals(e)) {
                return;
            }
        }

        entries.add(e);
    }

    /**
     * @see #entries
     */
    protected ArrayList<Entry> getEntries() {
        return entries;
    }


    public abstract @Nullable String getSchoolName();

    public ArrayList<Entry> filterUserFilters(@NonNull ArrayList<Entry> entries, Context context) {
        // get sharedPreferences
        final SharedPreferences sharedPreferences = context.getSharedPreferences("default", MODE_PRIVATE);

        if (!sharedPreferences.getBoolean("filter", false)) {
            // Filters are disabled
            return entries;
        }

        String number = sharedPreferences.getString("number", "");
        String letter = sharedPreferences.getString("letter", "");

        String[] classThings = new String[]{number, letter};

        String name = sharedPreferences.getString("name", "");

        String[] teacherThings = new String[]{name};

        Set<String> courses = sharedPreferences.getStringSet("courses", new HashSet<String>());
        String[] courseThings = courses.toArray(new String[courses.size()]);

        boolean courseFilterActive = courses.size() > 0 && !(courseThings[0].equals("") && courses.size() == 1);

        // Declare adjectives
        boolean displayGeneral = sharedPreferences.getBoolean("displayGeneral", true);
        boolean classFilterActive = !letter.isEmpty() || !number.isEmpty();
        boolean teacherFilterActive = !name.isEmpty();

        // Determine whether past should be filtered
        boolean filterPast = sharedPreferences.getBoolean("filterPast", true);

        if (!classFilterActive && !teacherFilterActive && !filterPast && !courseFilterActive) { // Let's not filter when no filter is enabled
            return entries;
        }


        for (int i = entries.size(); i > 0; i--) {
            Entry e = entries.get(i - 1);

            if (filterPast) {
                // Declare past adjective

                Calendar zeroOClockCalendar = Utility.zeroOClock(Calendar.getInstance());

                long today = zeroOClockCalendar.getTimeInMillis();
                if (e.getDate() != null) {
                    long entry = e.getDate().getTime();

                    // Entry is in the past if it was before today
                    boolean past = entry < today;

                    if (past) {
                        entries.remove(i - 1);

                        // Don't check other criteria as the entry is already gone
                        continue;
                    }
                }

                if (!classFilterActive && !teacherFilterActive && !courseFilterActive) {
                    // If only filtering past, don't check other criteria
                    continue;
                }

            }


            // Declare more adjectives

            boolean unterrichtsfrei = e.getInfo().contains("Unterrichtsfrei") || e.getInfo().contains("Unterrichtsende") || e.getInfo().contains("Unterrichtsschluss");

            boolean classInClass = thingsInString(e.getAffectedClass(), classThings, true, false);
            boolean classInInfo = thingsInString(e.getInfo(), classThings, false, false);

            boolean affectedClassEmpty = e.getAffectedClass().isEmpty();

            boolean teacherAppears = thingsInString(e.getReplacementTeacher(), teacherThings, true, false) // Teacher in teacher
                    || thingsInString(e.getInfo(), teacherThings, false, false); // Teacher in info

            boolean courseAppears = thingsInString(e.getInfo(), courseThings, true, true);

            boolean infoOnly = affectedClassEmpty && e.getLesson().isEmpty() && e.getReplacementTeacher().isEmpty() && !e.getInfo().isEmpty();

            // first possibility: Unterrichtsfrei / Unterrichtsende / Unterrichtsschluss
            if (unterrichtsfrei) {
                // pass, everyone is interested in that
            // second possibility: class appears or contains
            } else if (

                    (classInClass // test class in affected class
                            || (classInInfo && affectedClassEmpty) // test class in info if no affected class
                    ) && classFilterActive

            ) {
                // pass
            // third possibility: teacher appears
            } else if (teacherAppears && teacherFilterActive) {
                // pass
            // fourth possibility: course appears
            } else if (courseAppears && courseFilterActive) {
                // pass
            // fifth possibility: info only
            } else if (infoOnly && displayGeneral) {
                // pass
            } else {
                // fail
                entries.remove(i - 1);
            }
        }

        /*/ fill in data from sharedPreferences
        inputNumber.setText();
        inputLetter.setText(sharedPreferences.getString("letter", ""));
        inputName.setText(sharedPreferences.getString("name", ""));*/

        return entries;
    }

    /**
     * @param string     String that might contain the things.
     * @param things     Things that the String could contain.
     * @param ignoreCase Only some comparisons can be case-sensitive.
     *                   For details see <a href="https://notabug.org/fynngodau/DSBDirect/pulls/19">#19</a>
     * @param or         If true, an or condition is applied instead of an and condition.
     * @return Whether the String contains all or, if or is true, one of the things. If no things are given, false
     * is returned.
     */
    private boolean thingsInString(String string, String[] things, boolean ignoreCase, boolean or) {

        if (ignoreCase) {
            string = string.toLowerCase();

            for (int i = 0; i < things.length; i++) {
                things[i] = things[i].toLowerCase();
            }
        }


        String[] parts = string
                .replaceAll("</?s(trike)*>", "~") /* Bad to have strikethrough tags while filtering
                                                                       * ("<strike>6d</strike>" would contain an 'e')
                                                                       */
                .split("·");

        for (String part : parts) {
            /* If or is false, okay will be true at first and set to false once a thing is reached that part doesn't contain.
             * If or is true, okay will be false at first and set to true once a thing is reached that part does contain.
             * For a more detailed explanation, see #33
             */

            boolean okay = !or;
            for (String thing : things) {
                if (part.contains(thing) == or) {
                    okay = or;
                }
            }

            if (okay) {
                return true;
            }

        }

        // None of the parts contain all (or one of) the things
        return false;
    }

    public ArrayList<Entry> filterToday(@NonNull ArrayList<Entry> entries) {
        for (int i = entries.size(); i > 0; i--) {
            Entry entry = entries.get(i - 1);

            Date entryDate = entry.getDate();

            Calendar entryCalendar = Calendar.getInstance();
            entryCalendar.setTime(entryDate);

            Calendar todayCalendar = Calendar.getInstance();

            int entryDay = entryCalendar.get(Calendar.DAY_OF_YEAR);
            int todayDay = todayCalendar.get(Calendar.DAY_OF_YEAR);

            int entryYear = entryCalendar.get(Calendar.YEAR);
            int todayYear = todayCalendar.get(Calendar.YEAR);

            boolean yearMatches = entryYear == todayYear;
            boolean dayMatches = entryDay == todayDay;

            boolean sameDay = yearMatches && dayMatches;

            if (!sameDay) {
                entries.remove(entry);
            }
        }

        return entries;
    }

    public static Table[] readTableList(JSONArray jsonArray) throws JSONException {
        ArrayList<Table> tables = new ArrayList<>();

        parsing:
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonTable = jsonArray.getJSONObject(i);

            int contentType = jsonTable.getInt("ConType");
            // We can only handle html and images at the moment
            if (contentType == Table.CONTENT_HTML || contentType == Table.CONTENT_HTML_MYSTERY || contentType == Table.CONTENT_IMAGE) {

                String url = jsonTable.getString("Detail");

                // Test whether url is duplicate
                for (Table t :
                        tables) {
                    if (t.getUri().equals(url)) {
                        continue parsing;
                    }
                }

                Date publishedTime = Utility.parseLastUpdatedDate(jsonTable.getString("Date"));
                String title = jsonTable.getString("Title");

                // Not a duplicate; add
                tables.add(new Table(url, publishedTime, contentType, title));
            }

            // Recursion! Add all "Childs" of this table to tables
            Collections.addAll(tables, readTableList(jsonTable.getJSONArray("Childs")));

        }
        return tables.toArray(new Table[0]);
    }
}
