import { DecodeFn, EncodeFn } from "../types";
import * as util from "./util";

const decode: DecodeFn = (_msg) => {
  return [null];
};

const isObject = (v) =>
  typeof v === "object" && v.required !== undefined && v.value !== undefined;

const encode: EncodeFn = ({ value, path: initialPath }) => {
  const isObj = typeof value === "object";
  const allowPartial = isObj && value.allowPartial !== undefined ? value.allowPartial : false;
  const attr = initialPath.split(".").pop() || "";
  const pairs = isObj
    ? Object.entries(value as any[]).map(([k, v]) =>
        isObject(v)
          ? [k, v.value.toString(), v.required]
          : [k, v.toString(), false]
      )
    : [[attr, value]];
  const path = initialPath.endsWith(".") ? initialPath : initialPath.slice(0, initialPath.lastIndexOf('.') + 1);

  return {
    lookup: "Msg",
    header: {
      lookup: "Header",
      msgId: util.uniq("SET@"),
      msgType: "SET",
    },
    body: {
      lookup: "Body",
      request: {
        lookup: "Request",
        set: {
          allowPartial,
          updateObjs: [
            {
              lookup: "Set.UpdateObject",
              objPath: path,
              paramSettings: pairs
                .filter(([k]) => k !== "allowPartial")
                .map(([param, value, required]) => ({
                  lookup: "Set.UpdateParamSetting",
                  param,
                  value,
                  required,
                })),
            },
          ],
        },
      },
    },
  };
};

export default {
  decode,
  encode
};