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


    public static String buildQuery( String id, String sku, String status, String jobCardId, 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 queryBuilder = new QueryBuilder()
                .setTable( "cut_to_pack.master_bundle" )
                .setColumns( "*" )
                .where()
                .columnEquals( "id", id )
                .and()
                .columnEquals( "job_card_id", jobCardId )
                .and()
                .columnEquals( "sku", sku )
                .and()
                .columnEqualToOrGreaterThan("created_at" , startDate1 )
                .and()
                .columnEqualToOrLessThan( "created_at", endDate1 );


        if (! StringUtils.isNullOrEmpty( status ) ) {
            if (status.equalsIgnoreCase("1")) {
                queryBuilder.and()
                        .columnGreaterThan("is_received", "0");
            } else {
                queryBuilder.and()
                        .columnEquals("is_received", "0");
            }
        }
        queryBuilder.limit( count.intValue() );

        return queryBuilder.build();
    }
}
