import { ENCODER } from '../../index.js';
import { CREATE, UPDATE, RANGE_ERR, DELETE, DELETE_TEXT_FIELD, } from './types.js';
import { ModifyError } from './ModifyRes.js';
import { setCursor } from './setCursor.js';
import { write } from '../string.js';
// allow setting buffer in modify create for strings
// add compression handling for main buffer
// add compression handling for edge fields
export function writeString(lang, value, ctx, def, t, parentId, modifyOp) {
    const isBuffer = value instanceof Uint8Array;
    if (value === null || value === '') {
        if (modifyOp === UPDATE) {
            if (ctx.len + 11 /* SIZE.DEFAULT_CURSOR */ + 2 > ctx.max) {
                return RANGE_ERR;
            }
            setCursor(ctx, def, t.prop, t.typeIndex, parentId, modifyOp);
            if (lang === 0) {
                ctx.buf[ctx.len++] = DELETE;
            }
            else {
                ctx.buf[ctx.len++] = DELETE_TEXT_FIELD;
                ctx.buf[ctx.len++] = lang;
            }
        }
    }
    else {
        if (!t.validation(value, t)) {
            return new ModifyError(t, value);
        }
        let size = isBuffer
            ? value.byteLength
            : ENCODER.encode(value).byteLength + 6;
        if (ctx.len + 11 /* SIZE.DEFAULT_CURSOR */ + 11 + size > ctx.max) {
            return RANGE_ERR;
        }
        if (modifyOp === CREATE) {
            def.seperateSort.bufferTmp[t.prop] = 2;
            ctx.hasSortField++;
        }
        setCursor(ctx, def, t.prop, t.typeIndex, parentId, modifyOp);
        // TODO if buffer check if second byte is zero or one
        // modOp | size u32 | stringprotocol | string
        ctx.buf[ctx.len] = modifyOp;
        ctx.len += 5;
        if (isBuffer) {
            ctx.buf.set(value, ctx.len);
        }
        else {
            const isNoCompression = t.compression === 0;
            // @ts-ignore stupid str
            size = write(ctx.buf, value, ctx.len, isNoCompression, lang);
        }
        let sizepos = ctx.len + 1 - 5;
        ctx.len += size;
        ctx.buf[sizepos++] = size;
        ctx.buf[sizepos++] = size >>>= 8;
        ctx.buf[sizepos++] = size >>>= 8;
        ctx.buf[sizepos] = size >>>= 8;
    }
}
//# sourceMappingURL=string.js.map