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 PurchaseOrderCTPQueryBuilder {
    public static String buildQuery(String purchaseOrderCode, String articleName, String createdBy, String startDate, String endDate, Long count ){
        // format date
        String formattedDate;
        String formattedEndDate;
        String startDate1 = "";
        String endDate1 = "";
        String purchaseOrderCode1 = purchaseOrderCode == null ? "" : purchaseOrderCode;
        String articleName1 = articleName == null ? "" : articleName;
        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() );
            }
        }

        return (new QueryBuilder())
                .setTable("cut_to_pack.purchase_order")
                .setColumns("*")
                .where()
                .columnEquals("created_by", createdBy)
                .and()
                .columnLike("purchase_order_code", "%" + purchaseOrderCode1 + "%")
                .and()
                .columnLike("article_name", articleName)
                .and()
                .columnEqualToOrGreaterThan("created_at", startDate1)
                .and()
                .columnEqualToOrLessThan("created_at", endDate1)
                .limit(count.intValue())
                .build();
    }
}
