/*
 * 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;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

import static android.content.Context.MODE_PRIVATE;

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

    protected String mHtml;
    protected final Context mContext;
    protected XmlPullParser mParser;

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public Reader(String html, Context context) {
        // pass on value
        mHtml = html;
        mContext = context;

    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public ArrayList<Entry> read() throws ParseException {

        return null;
    }

    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 name = sharedPreferences.getString("name", "");

        // Declare adjectives
        boolean displayGeneral = sharedPreferences.getBoolean("displayGeneral", false);
        boolean classFilterActive = letter.length() > 0 || number.length() > 0;
        boolean teacherFilterActive = name.length() > 0;

        if (!classFilterActive && !teacherFilterActive) { // 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);

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

            if (filterPast) {
                // Declare past adjective

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

                long today = zeroOClockCalendar.getTimeInMillis();
                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;
                }

            }


            // Declare more adjectives

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

            boolean classInClass = e.getAffectedClass().contains(number) && e.getAffectedClass().contains(letter);
            boolean classInInfo = e.getInfo().contains(number) && e.getInfo().contains(letter);
            boolean affectedClassEmpty = e.getAffectedClass().length() == 0;

            boolean teacherAppears = e.getReplacementTeacher().contains(name) || e.getInfo().contains(name);

            boolean infoOnly = affectedClassEmpty && e.getLesson().length() == 0 && e.getReplacementTeacher().length() == 0 && e.getInfo().length() > 0;

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

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

            ) {
                // pass
            // second possibility: teacher appears
            } else if (teacherAppears && teacherFilterActive) {
                // pass
            // third 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;
    }

    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;
    }

    private void dumpAll() {
        try {
            while (true) {
                int eventType = mParser.getEventType();
                String name = mParser.getName();
                String text = mParser.getText();
                int depth = mParser.getDepth();

                Log.d("DUMP", "(" + depth + ") e" + eventType + "   " + name + "      " + text);

                mParser.next();
            }

        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private String filterLongText(String input) {
        if (input.length() > 120) {
            return "[REDACTED]";
        } else {
            return input;
        }
    }

    public static Table[] readTableList(String json) throws JSONException {
        JSONArray jsonArray = new JSONArray(json);

        Table[] tables = new Table[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonTable = jsonArray.getJSONObject(i);
            String url = jsonTable.getString("timetableurl");
            Date publishedTime = Utility.parseLastUpdatedDate(jsonTable.getString("timetabledate"));

            if (jsonTable.getBoolean("ishtml")) {
                tables[i] = new HtmlTable(url, publishedTime);
            } else {
                tables[i] = new ImageTable(url, publishedTime);
            }

        }

        return tables;
    }
}
