package com.kbs.kbsintranett;

import android.content.Context;
import android.content.SharedPreferences; // NYTT
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class CacheManager {
    private static final String FILE_CALENDAR = "cache_calendar.json";
    private static final String FILE_NEWS = "cache_news.json";
    private static final String FILE_HANDBOOK = "cache_handbook.json";
    private static final String FILE_TASKS = "cache_tasks.json";

    private static final String TAG = "CacheManager";
    private static final Gson gson = new Gson();

    // NYTT: SharedPreferences for tidsstempler
    private static final String PREFS_CACHE = "kbs_cache_prefs";

    // --- KALENDER ---
    public static void saveCalendarEvents(Context context, List<CalendarEvent> events) {
        saveList(context, FILE_CALENDAR, events);
        setLastFetchTime(context, "calendar"); // NYTT
    }

    public static List<CalendarEvent> getCachedCalendarEvents(Context context) {
        Type type = new TypeToken<List<CalendarEvent>>() {}.getType();
        List<CalendarEvent> list = loadList(context, FILE_CALENDAR, type);
        return list != null ? list : new ArrayList<>();
    }

    // --- NYHETER ---
    public static void saveNewsPosts(Context context, List<WpPost> posts) {
        saveList(context, FILE_NEWS, posts);
        setLastFetchTime(context, "news"); // NYTT
    }

    public static List<WpPost> getCachedNewsPosts(Context context) {
        Type type = new TypeToken<List<WpPost>>() {}.getType();
        List<WpPost> list = loadList(context, FILE_NEWS, type);
        return list != null ? list : new ArrayList<>();
    }

    // --- HÅNDBOK ---
    public static void saveHandbookItems(Context context, List<HandbookItem> items) {
        saveList(context, FILE_HANDBOOK, items);
        // Håndboken endres sjelden, trenger kanskje ikke tidssjekk, men greit å ha
    }

    public static List<HandbookItem> getCachedHandbookItems(Context context) {
        Type type = new TypeToken<List<HandbookItem>>() {}.getType();
        List<HandbookItem> list = loadList(context, FILE_HANDBOOK, type);
        return list != null ? list : new ArrayList<>();
    }

    // --- OPPGAVER ---
    public static void saveTasks(Context context, List<TaskItem> tasks) {
        saveList(context, FILE_TASKS, tasks);
        setLastFetchTime(context, "tasks"); // NYTT
    }

    public static List<TaskItem> getTasks(Context context) {
        Type type = new TypeToken<List<TaskItem>>() {}.getType();
        List<TaskItem> list = loadList(context, FILE_TASKS, type);
        return list != null ? list : new ArrayList<>();
    }

    // --- LOGIKK FOR TID ---

    private static void setLastFetchTime(Context context, String key) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_CACHE, Context.MODE_PRIVATE);
        prefs.edit().putLong(key + "_timestamp", System.currentTimeMillis()).apply();
    }

    /**
     * Sjekker om cachen er gyldig.
     * @param maxAgeMinutes Hvor gammel cachen kan være før vi henter på nytt (f.eks. 60 minutter).
     *                      Hvis push fungerer, kan vi sette denne høyt!
     */
    public static boolean isCacheValid(Context context, String key, int maxAgeMinutes) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_CACHE, Context.MODE_PRIVATE);
        long lastTime = prefs.getLong(key + "_timestamp", 0);
        long diff = System.currentTimeMillis() - lastTime;
        // Konverter minutter til millisekunder
        long maxDiff = maxAgeMinutes * 60 * 1000L;

        return diff < maxDiff;
    }

    // Metode for å tvinge oppdatering neste gang (brukes av FCM)
    public static void invalidateCache(Context context, String key) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_CACHE, Context.MODE_PRIVATE);
        prefs.edit().remove(key + "_timestamp").apply();
    }

    // --- GENERISKE HJELPEMETODER (Uendret) ---

    private static <T> void saveList(Context context, String filename, List<T> list) {
        if (context == null || list == null) return;
        new Thread(() -> {
            try {
                String json = gson.toJson(list);
                FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
                fos.write(json.getBytes());
                fos.close();
            } catch (Exception e) {
                Log.e(TAG, "Feil ved lagring av cache: " + filename, e);
            }
        }).start();
    }

    private static <T> List<T> loadList(Context context, String filename, Type type) {
        if (context == null) return null;
        File file = new File(context.getFilesDir(), filename);
        if (!file.exists()) return null;

        try {
            FileInputStream fis = context.openFileInput(filename);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader bufferedReader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            fis.close();
            return gson.fromJson(sb.toString(), type);
        } catch (Exception e) {
            Log.e(TAG, "Feil ved lesing av cache: " + filename, e);
            return null;
        }
    }
}