package com.imprimelibros.erp.datatables;

import jakarta.servlet.http.HttpServletRequest;
import java.util.*;

public class DataTablesParser {
    public static DataTablesRequest from(HttpServletRequest req) {
        DataTablesRequest dt = new DataTablesRequest();
        dt.draw   = parseInt(req.getParameter("draw"), 0);
        dt.start  = parseInt(req.getParameter("start"), 0);
        dt.length = parseInt(req.getParameter("length"), 10);

        if (req.getParameter("search[value]") != null) {
            dt.search.value = req.getParameter("search[value]");
            dt.search.regex = Boolean.parseBoolean(req.getParameter("search[regex]"));
        }

        for (int i=0;; i++) {
            String data = req.getParameter("columns["+i+"][data]");
            if (data == null) break;
            DataTablesRequest.Column c = new DataTablesRequest.Column();
            c.data = data;
            c.name = Optional.ofNullable(req.getParameter("columns["+i+"][name]")).orElse(data);
            c.searchable = Boolean.parseBoolean(Optional.ofNullable(req.getParameter("columns["+i+"][searchable]")).orElse("true"));
            c.orderable  = Boolean.parseBoolean(Optional.ofNullable(req.getParameter("columns["+i+"][orderable]")).orElse("true"));
            c.search.value = Optional.ofNullable(req.getParameter("columns["+i+"][search][value]")).orElse("");
            dt.columns.add(c);
        }
        for (int i=0;; i++) {
            String colIdx = req.getParameter("order["+i+"][column]");
            if (colIdx == null) break;
            DataTablesRequest.Order o = new DataTablesRequest.Order();
            o.column = parseInt(colIdx,0);
            o.dir = Optional.ofNullable(req.getParameter("order["+i+"][dir]")).orElse("asc");
            dt.order.add(o);
        }

        // guarda TODOS los params crudos (para filtros custom)
        req.getParameterMap().forEach((k,v) -> dt.raw.put(k, v!=null && v.length>0 ? v[0] : null));
        return dt;
    }
    private static int parseInt(String s, int def){ try{return Integer.parseInt(s);}catch(Exception e){return def;}}
}