package de.sebse.fuplanner.services.kvv;

import android.content.Context;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import de.sebse.fuplanner.services.kvv.types.Announcement;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkError;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;

public class ModulesAnnouncements extends PartModules<ArrayList<Announcement>> {

    ModulesAnnouncements(Login login, ModulesList list, Context context) {
        super(login, list, context);
    }

    @Override
    protected ArrayList<Announcement> getPart(Modules.Module module) {
        return module.announcements;
    }

    @Override
    protected boolean setPart(Modules.Module module, ArrayList<Announcement> part) {
        boolean changed = module.announcements == null || module.announcements.hashCode() != part.hashCode();
        module.announcements = part;
        return changed;
    }

    @Override
    protected void upgrade(final String ID, final NetworkCallback<ArrayList<Announcement>> callback, final NetworkErrorCallback errorCallback) {
        if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
            errorCallback.onError(new NetworkError(101204, 500, "Currently running in offline mode!"));
            return;
        }
        super.get(String.format("https://kvv.imp.fu-berlin.de/direct/announcement/site/%s.json?n=999999&d=999999999", ID), mLogin.getLoginToken().getCookies(), response -> {
            String body = response.getParsed();
            if (body == null) {
                errorCallback.onError(new NetworkError(101201, 403, "No announcements retrieved!"));
                return;
            }
            ArrayList<Announcement> announcements = new ArrayList<>();
            JSONArray sites;
            try {
                JSONObject json = new JSONObject(body);
                sites = json.getJSONArray("announcement_collection");
            } catch (JSONException e) {
                e.printStackTrace();
                errorCallback.onError(new NetworkError(101202, 403, "Cannot parse announcements!"));
                return;
            }

            for (int i = 0; i < sites.length(); i++) {
                try {
                    JSONObject site = sites.getJSONObject(i);
                    String id = site.getString("announcementId");
                    String title = site.getString("title");
                    String text = site.getString("body");
                    text = String.valueOf(fromHtml(text));
                    String createdBy = site.getString("createdByDisplayName");
                    long createdOn = site.getLong("createdOn");

                    // Extract attachment links
                    JSONArray attachments = site.getJSONArray("attachments");
                    ArrayList<String> urls = new ArrayList<>();
                    for (int j = 0; j < attachments.length(); j++) {
                        urls.add(attachments.getJSONObject(j).optString("url", null));
                    }

                    announcements.add(new Announcement(id, title, text, createdBy, createdOn, urls));
                } catch (JSONException e) {
                    log.e(new NetworkError(101205, 403, "Cannot parse announcements!"));
                    log.e("ID:", i, "JSON:", sites);
                    e.printStackTrace();
                    return;
                }
            }

            // Empty announcements *may be* because token is invalid -> check
            if (announcements.size() == 0)
                mLogin.testLoginToken(token -> callback.onResponse(announcements), errorCallback);
            else
                callback.onResponse(announcements);
        }, error -> errorCallback.onError(new NetworkError(101203, error.networkResponse.statusCode, "Cannot get announcements!")));
    }
}
