package com.utopiaindustries.querybuilder.ctp;

import com.utopiaindustries.querybuilder.QueryBuilder;
import com.utopiaindustries.util.CTPDateTimeFormat;
import com.utopiaindustries.util.StringUtils;

import java.time.LocalDate;

public class BundleQueryBuilder {

    public static String buildQuery(String id, String sku, String jobCardId, String masterId, String type, String status, String startDate, String endDate, Long count) {
        // format date
        String formattedDate;
        String formattedEndDate;
        String startDate1 = "";
        String endDate1 = "";
        if (!StringUtils.isNullOrEmpty(startDate)) {
            formattedDate = CTPDateTimeFormat.getMySQLFormattedDateString(startDate, CTPDateTimeFormat.HTML5_DATE_INPUT_FORMAT);
            formattedEndDate = CTPDateTimeFormat.getMySQLFormattedDateString(endDate, CTPDateTimeFormat.HTML5_DATE_INPUT_FORMAT);
            startDate1 = String.format("'%s 00:00:01'", formattedDate);
            if (!StringUtils.isNullOrEmpty(endDate)) {
                endDate1 = String.format("'%s 23:59:59'", formattedEndDate);
            } else {
                endDate1 = String.format("'%s 23:59:59'", LocalDate.now());
            }
        }


        QueryBuilder qb = new QueryBuilder()
                .setTable("cut_to_pack.bundle")
                .setColumns("*")
                .where()
                .columnEquals("id", id)
                .and()
                .columnEquals("sku", sku)
                .and()
                .columnEquals("job_card_id", jobCardId)
                .and()
                .columnEquals("type", type)
                .and()
                .columnEquals("master_bundle_id", masterId);


        if (! StringUtils.isNullOrEmpty( status ) ) {
            if (status.equalsIgnoreCase("1")) {
                qb.and()
                        .columnGreaterThan("master_bundle_id", "0");
            } else {
                qb.and()
                        .columnEquals("master_bundle_id", "0");
            }
        }
        qb.and()
                .columnEqualToOrGreaterThan("created_at", startDate1)
                .and()
                .columnEqualToOrLessThan("created_at", endDate1)
                .limit(count.intValue());

        return qb.build();
    }
}
