package xyz.wbsite.wsqlite;

import java.util.ArrayList;
import java.util.List;

public class Where {
    private String sql;
    private Object[] args;

    private Where() {
    }

    public String getSql() {
        return sql;
    }

    public void setSql(String sql) {
        this.sql = sql;
    }

    public Object[] getArgs() {
        return args;
    }

    public void setArgs(Object[] args) {
        this.args = args;
    }

    public Where(String sql, Object[] args) {
        this.sql = sql;
        this.args = args;
    }

    public static Builder builder() {
        return new Builder();
    }

    public static class Builder {
        private StringBuilder sb = new StringBuilder();
        private List<Object> argsList = new ArrayList<>();

        public Builder eq(String name, Object value) {
            return eq(true, name, value);
        }

        public Builder like(String name, Object value) {
            return like(true, name, value);
        }

        public Builder isNull(String name, Object value) {
            return isNull(true, name, value);
        }

        public Builder isNotNull(String name, Object value) {
            return isNotNull(true, name, value);
        }

        public Builder eq(boolean condition, String name, Object value) {
            if (condition) {
                sb.append(sb.length() > 0 ? " and " : " where ").append(name).append(" = ? ");
                argsList.add(value);
            }
            return this;
        }

        public Builder like(boolean condition, String name, Object value) {
            if (condition) {
                sb.append(sb.length() > 0 ? " and  " : " where ").append(name).append("like ?");
                argsList.add(value);
            }
            return this;
        }

        public Builder isNull(boolean condition, String name, Object value) {
            if (condition) {
                sb.append(sb.length() > 0 ? " and " : " where ").append(name).append("is null");
                argsList.add(value);
            }
            return this;
        }

        public Builder isNotNull(boolean condition, String name, Object value) {
            if (condition) {
                sb.append(sb.length() > 0 ? " and " : " where ").append(name).append("is not null");
                argsList.add(value);
            }
            return this;
        }

        public Where build() {
            return new Where(sb.toString(), argsList.toArray());
        }
    }
}
