package org.schabi.newpipe.util;

import android.content.Context;
import android.text.TextUtils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

public final class CookieUtils {
    private CookieUtils() {
    }

    public static String concatCookies(final Collection<String> cookieStrings) {
        final Set<String> cookieSet = new HashSet<>();
        for (final String cookies : cookieStrings) {
            cookieSet.addAll(splitCookies(cookies));
        }
        return TextUtils.join("; ", cookieSet).trim();
    }

    public static Set<String> splitCookies(final String cookies) {
        return new HashSet<>(Arrays.asList(cookies.split("; *")));
    }


    public static Map<String, String> parseCookieHeader(String cookieHeader) {
        if(cookieHeader == null) {
            return Collections.emptyMap();
        }
        Map<String, String> cookies = new HashMap<>();
        String[] cookieArray = cookieHeader.split(";");
        for (String cookie : cookieArray) {
            String[] parts = cookie.split("=", 2);
            if (parts.length == 2) {
                cookies.put(parts[0].trim(), parts[1].trim());
            }
        }
        return cookies;
    }

    public static String formatCookieNetscape(String domain, String path, boolean secure, long expiration, String name, String value) {
        String domainFlag = domain.startsWith(".") ? "TRUE" : "FALSE";
        String secureFlag = secure ? "TRUE" : "FALSE";
        return String.format("%s\t%s\t%s\t%s\t%d\t%s\t%s\n", domain, domainFlag, path, secureFlag, expiration, name, value);
    }

    public static void exportCookiesToNetscape(Context context, String cookieHeader, String domain, String path, boolean secure, long expiration, String filename) {
        Map<String, String> cookies = parseCookieHeader(cookieHeader);
        File cacheDir = context.getCacheDir();
        File file = new File(cacheDir, filename);

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            writer.write("# Netscape HTTP Cookie File\n");
            writer.write("# This file is generated by an Android app\n");
            writer.write("#\n");
            writer.write("# This file is formatted for Netscape's cookie format\n");

            for (Map.Entry<String, String> entry : cookies.entrySet()) {
                String cookieLine = formatCookieNetscape(domain, path, secure, expiration, entry.getKey(), entry.getValue());
                writer.write(cookieLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void exportCookiesToNetscapeYouTube(Context context, String cookieHeader) {
        exportCookiesToNetscape(context, cookieHeader, ".youtube.com", "/", false, 0, "cookies.youtube.txt");
    }
}
