package com.kbs.kbsintranett;

import android.content.Context;
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 TAG = "CacheManager";
    private static final Gson gson = new Gson();

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

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

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

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

    // --- GENERISKE HJELPEMETODER ---

    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();
                Log.d(TAG, "Lagret cache til " + filename);
            } 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;
        }
    }
    private static final String FILE_TASKS = "cache_tasks.json";

    public static void saveTasks(Context context, List<TaskItem> tasks) {
        saveList(context, FILE_TASKS, tasks);
    }

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