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 JobCardQueryBuilder {

    public static String buildQuery(String code, String createdBy, String status, String inventoryStatus, String customer, String lotNumber, String purchaseOrderId, String locationSiteId, 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() );
            }
        }

        return (new QueryBuilder())
                .setTable("cut_to_pack.job_card")
                .setColumns("*")
                .where()
                .columnEquals("created_by", createdBy)
                .and()
                .columnLike("code", "%" + code + "%")
                .and()
                .columnEquals("status", status)
                .and()
                .columnEquals("inventory_status", inventoryStatus)
                .and()
                .columnEquals("customer", customer)
                .and()
                .columnEquals("lot_number", lotNumber)
                .and()
                .columnEquals("purchase_order_id", purchaseOrderId)
                .and()
                .columnEquals("location_site_id", locationSiteId)
                .and()
                .columnEqualToOrGreaterThan("created_at", startDate1)
                .and()
                .columnEqualToOrLessThan("created_at", endDate1)
                .limit(count.intValue())
                .build();
    }
}
