drop function if exists mmt_staging2.fn_fthlg_trs_block;
CREATE OR REPLACE FUNCTION mmt_staging2.fn_fthlg_trs_block(p_client_id int,p_function_id int, p_file_format text,
p_sheet_mnemonic text, p_file_syspk int)
   RETURNS text AS $$
   
   
   declare __client_id int :=p_client_id;
   declare __function_id int :=p_function_id;
   declare __file_format text  :=p_file_format;
   declare __sheet_mnemonic text :=p_sheet_mnemonic;
   declare __file_syspk int :=p_file_syspk;
   declare v_state   text;
   declare v_msg     text;
   declare v_detail  text;
   declare v_hint    text;
   declare v_context text;   
   declare _error int;
   declare v_block text;  
  
 begin




/***********************************************************************************
Function Name:fn_FTHLG_TRS_Block
Function Desc: This function populates data into staging2 blocks
File Format: FTHLG
Sheet Format: FTHLG_TRS
Creation Date: 
Updation Date:
Author: compegence team
Function Call: select mmt_staging2.fn_fthlg_trs_block(20,1,'FTHLG','FTHLG_TRS',259);
************************************************************************************/

 SET search_path TO  mmt_staging2;
	 	 
truncate mmt_staging2.FTHLG_TRS_H1_INT;
truncate  mmt_staging2.FTHLG_TRS_H1_Block;
truncate  mmt_staging2.FTHLG_TRS_SPEC_Block;
truncate  mmt_staging2.FTHLG_TRS_Engine_RPM_Block;
truncate  mmt_staging2.FTHLG_TRS_Trailer_Block;
truncate mmt_staging2.stg_specific_table_fthlg_trs;
truncate mmt_staging2.stg_process_table_fthlg_trs;


execute 'delete from mmt_ods.fw_jobctrl_file_sheet_block_run_schedule where file_syspk='||p_file_syspk||' and sheet_mnemonic='''||p_sheet_mnemonic||'''';

execute 'update mmt_ods.mmt_config a
set row_number_start=null,
row_previous_number=null,
row_read_end=null,
run_time=null
where a.file_format='''||p_file_format||''' and a.sheet_mnemonic='''||p_sheet_mnemonic||''''; 

/* transfer data from generic to specific for ftdry*/

execute 'insert into mmt_staging2.stg_specific_table_fthlg_trs
select * from mmt_staging1.mmt_staging_generic_table a
where  a.file_format='''||p_file_format||''' and a.sheet_mnemonic='''||p_sheet_mnemonic||'''
and a.file_syspk='||p_file_syspk||'';

/* trimming data */
update mmt_staging2.stg_specific_table_fthlg_trs set column2 =  TRIM (TRAILING FROM column2 );
update mmt_staging2.stg_specific_table_fthlg_trs set column2 =  TRIM (LEADING FROM column2 );



update mmt_ods.mmt_config set F1_modified =  TRIM (TRAILING FROM F1_modified); 
update mmt_ods.mmt_config set F1_modified =  TRIM (LEADING FROM F1_modified); 
update mmt_ods.mmt_config set F1_source=F1_modified;
update mmt_ods.mmt_config set F1_source =  TRIM (TRAILING FROM F1_source); 
update mmt_ods.mmt_config set F1_source =  TRIM (LEADING FROM F1_source);

/* keyword match in config table*/
execute 'update mmt_ods.mmt_config a  
set row_number_start=(select min(b.row_number)
from mmt_staging2.stg_specific_table_fthlg_trs  b
where F1_source=column2
and b.is_rownumber_fetched is null)
where a.row_number_start is null and a.file_format='''||p_file_format||''' and a.sheet_mnemonic='''||p_sheet_mnemonic||'''';

/* reverese update in process table for match*/
execute 'update mmt_staging2.stg_specific_table_fthlg_trs  a  
set is_rownumber_fetched=1
from mmt_ods.mmt_config  b
where F1_source=column2
and b.row_number_start=a.row_number
and is_rownumber_fetched is null and a.file_format='''||p_file_format||''' and a.sheet_mnemonic='''||p_sheet_mnemonic||'''';


execute 'update mmt_ods.mmt_config  a  set row_previous_number=row_number_start-1 
where a.file_format='''||p_file_format||''' and a.sheet_mnemonic='''||p_sheet_mnemonic||'''';


/*  update config files for row numbers start, end */
execute 'update mmt_ods.mmt_config a
set row_read_end= (select b.row_number_start
from mmt_ods.mmt_config b 
where b.syspk=a.syspk+1 ) 
where a.file_format='''||p_file_format||''' and a.sheet_mnemonic='''||p_sheet_mnemonic||'''';

/* config file last field update as null otherwise it picks up next format row number*/
execute 'update mmt_ods.mmt_config a set row_read_end = null where f1_modified =''Trailer Details'' and
a.file_format='''||p_file_format||''' and a.sheet_mnemonic='''||p_sheet_mnemonic||'''';

/*inserting run_time in config*/
execute 'update mmt_ods.mmt_config a 
set run_time=current_timestamp where a.file_format='''||p_file_format||''' and a.sheet_mnemonic='''||p_sheet_mnemonic||'''';

/* tagging ranks for each block in process table*/
execute 'insert into mmt_staging2.stg_process_table_fthlg_trs
select a.* , RANK () OVER ( ORDER BY row_number),b.rank_tag as rank_tag
from  mmt_staging2.stg_specific_table_fthlg_trs a
join mmt_ods.mmt_config  b 
on a.row_number >row_number_start
and (a.row_number< row_read_end or row_read_end is null)
and f1_modified=''Tractor specifications sheet'' and b.file_format='''||p_file_format||''' and b.sheet_mnemonic='''||p_sheet_mnemonic||'''
order by a.row_number';



execute 'insert into mmt_staging2.stg_process_table_fthlg_trs
select a.* , RANK () OVER ( ORDER BY row_number),b.rank_tag as rank_tag
from  mmt_staging2.stg_specific_table_fthlg_trs a
join mmt_ods.mmt_config  b 
on a.row_number >row_number_start
and (a.row_number< row_read_end or row_read_end is null)
and f1_modified=''Tractor Specifications'' and b.file_format='''||p_file_format||''' and b.sheet_mnemonic='''||p_sheet_mnemonic||'''
order by a.row_number';

execute 'insert into mmt_staging2.stg_process_table_fthlg_trs
select a.* , RANK () OVER ( ORDER BY row_number),b.rank_tag as rank_tag
from  mmt_staging2.stg_specific_table_fthlg_trs a
join mmt_ods.mmt_config  b 
on a.row_number >row_number_start
and (a.row_number< row_read_end or row_read_end is null)
and f1_modified=''Engine RPM Data:'' and  b.file_format='''||p_file_format||''' and b.sheet_mnemonic='''||p_sheet_mnemonic||'''
order by a.row_number';

execute 'insert into mmt_staging2.stg_process_table_fthlg_trs
select a.* , RANK () OVER ( ORDER BY row_number),b.rank_tag as rank_tag
from  mmt_staging2.stg_specific_table_fthlg_trs a
join mmt_ods.mmt_config  b 
on a.row_number >row_number_start
and (a.row_number< row_read_end or row_read_end is null)
and f1_modified=''Trailer Details'' and b.file_format='''||p_file_format||''' and b.sheet_mnemonic='''||p_sheet_mnemonic||'''
order by a.row_number';


/*inserting data into FTHLG_TRS_H1_INT*/
v_block:='FTHLG_TRS_H1_Block';

insert into  mmt_staging2.FTHLG_TRS_H1_INT
(column2,column3,column4,column5,column6,column7,rank)
select column2,column3,column4,column5,column6,column7,rank from mmt_staging2.stg_process_table_fthlg_trs a
where rank_tag='FTHLG_TRS_H1' order by rank;


insert into mmt_staging2.FTHLG_TRS_H1_INT(column2) values ('Date of Test');

insert into mmt_staging2.FTHLG_TRS_H1_INT(column2) values ('Report Date');

insert into mmt_staging2.FTHLG_TRS_H1_INT(column2) values ('Type of Road');

insert into mmt_staging2.FTHLG_TRS_H1_INT (column2) values ('Tractor Hitch Height from Ground, mm');

insert into mmt_staging2.FTHLG_TRS_H1_INT  (column2) values ('Tractor Rear Wheel Center to Hitch Point Center Distance, mm');


update mmt_staging2.FTHLG_TRS_H1_INT a
set column3=(select column5 from mmt_staging2.FTHLG_TRS_H1_INT b
where trim(a.column2)=trim(b.column4)
and b.column4='Date of Test')
where  a.column2='Date of Test';

update mmt_staging2.FTHLG_TRS_H1_INT a
set column3=(select column7 from mmt_staging2.FTHLG_TRS_H1_INT b
where trim(a.column2)=trim(b.column6)
and b.column6='Report Date')
where  a.column2='Report Date';

update mmt_staging2.FTHLG_TRS_H1_INT a
set column3=(select column6 from mmt_staging2.FTHLG_TRS_H1_INT b
where trim(a.column2)=trim(b.column5)
and b.column5='Type of Road')
where  a.column2='Type of Road';

update mmt_staging2.FTHLG_TRS_H1_INT a
set column3=(select column6 from mmt_staging2.FTHLG_TRS_H1_INT b
where trim(a.column2)=trim(b.column5)
and b.column5='Tractor Hitch Height from Ground, mm')
where  a.column2='Tractor Hitch Height from Ground, mm';


update mmt_staging2.FTHLG_TRS_H1_INT a
set column3=(select column6 from mmt_staging2.FTHLG_TRS_H1_INT b
where trim(a.column2)=trim(b.column5)
and b.column5='Tractor Rear Wheel Center to Hitch Point Center Distance, mm')
where  a.column2='Tractor Rear Wheel Center to Hitch Point Center Distance, mm';

/*inserting data into block -.FTHLG_TRS_H1_Block*/



perform mmt_staging2.fn_jobctrl_block_begin(__client_id,__function_id,__file_syspk,
'FTHLG_TRS_H1_Block',__file_format,__sheet_mnemonic,1); 


insert into  mmt_staging2.FTHLG_TRS_H1_Block
(
dummy_f,
Report_Reference_No,
Objective_Of_Test,
Background_of_Test,
Job_Order_No,    
Test_Location,
Gradient_Slope_1_Degree,
Gradient_Slope_2_Degree,
Tractor_Hitch_Type,
Test_Engineer,
Test_Operator,
Date_of_Test,
Report_Date,
Type_of_Road,
Tractor_Hitch_Height_from_Ground_mm,
Tractor_Rear_Wheel_Center_to_Hitch_Point_Center_Distance_mm
)
SELECT *
FROM   crosstab(
       'SELECT  unnest(''{column3}''::text[]) AS col
             , row_number() OVER ()
             , unnest(ARRAY[column3::text]) AS val
        FROM mmt_staging2.FTHLG_TRS_H1_INT
        ORDER  BY generate_series(1,15),rank,2'
   ) t (col text,a_1 text,a_2 text,a_3 text,a_4 text,a_5 text,a_6 text,a_7 text,a_8 text,a_9 text,a_10 text,
  a_11 text,a_12 text,a_13 text,a_14 text,a_15 text);
  

delete from  mmt_staging2.FTHLG_TRS_H1_Block where dummy_f is null ;
execute 'update   mmt_staging2.FTHLG_TRS_H1_Block set 
client_id='||p_client_id||',
function_id='||p_function_id||',
file_syspk='||p_file_syspk||',
file_format='''||p_file_format||''',
sheet_mnemonic='''||p_sheet_mnemonic||'''';

perform mmt_staging2.fn_jobctrl_block_end(__file_syspk,'FTHLG_TRS_H1_Block'); 



/*inserting data into block -FTHLG_TRS_SPEC_Block*/


perform mmt_staging2.fn_jobctrl_block_begin(__client_id,__function_id,__file_syspk,
'FTHLG_TRS_SPEC_Block',__file_format,__sheet_mnemonic,2); 
v_block:='FTHLG_TRS_SPEC_Block';

insert into mmt_staging2.FTHLG_TRS_SPEC_Block
(
dummy_f,
Tractor_Model,
Tractor_Make,
Tractor_Sr_No,
Tractor_Engine_HP,
FIP_Type,
hour_Meter_Reading,
Steering_Type,
Transmission_Type,
Wheel_Drive_Type_WD,
EGR_Yes_No,
Brake_Type,
PTO_Type,
Standard_PTO_Speed_RPM,
EPTO_Speed_RPM,
Front_Tyre_Make,
Front_Tyre_Size,
Front_Tyre_Pressure_psi,
Rear_Tyre_Make,                         
Rear_Tyre_Size,
Rear_Tyre_Pressure_psi ,   
Tractor_Weight_kg_Front ,
Tractor_Weight_kg_Rear ,
Tractor_Weight_kg_Total,
Ballasted_Tractor_Accessories,
Mechanical_Ballast_Rear,
Mechanical_Ballast_Rear_in_KG ,
Water_Ballast_Rear_75,
Mechanical_Ballast_Front_in_Kg,
Mechanical_Ballast_Front,
Total_Ballast_Weight
)
SELECT *
FROM   crosstab(
       'SELECT  unnest(''{column3,column4,column5,column6,column7}''::text[]) AS col
             , row_number() OVER ()
             , unnest(ARRAY[column3::text,column4::text,column5::text,column6::text,column7::text]) AS val
        FROM  mmt_staging2.stg_process_table_fthlg_trs where rank_tag=''FTHLG_TRS_SPEC''
        ORDER  BY generate_series(1,15),rank,2'
   ) t (col text,a_1 text,a_2 text,a_3 text,a_4 text,a_5 text,a_6 text,a_7 text,a_8 text,
   a_9 text,a_10 text,a_11 text,a_12 text,a_13 text,a_14 text,a_15 text,a_16 text,a_17 text,a_18 text,a_19 text,a_20 text,a_21 text,
  a_22 text,a_23 text,a_24 text,a_25 text,a_26 text,a_27 text,a_28 text,a_29 text,a_30 text);

delete from mmt_staging2.FTHLG_TRS_SPEC_Block where tractor_make is null and tractor_sr_no is null;


delete from  mmt_staging2.FTHLG_TRS_SPEC_Block where dummy_f is null ;
execute 'update   mmt_staging2.FTHLG_TRS_SPEC_Block set 
client_id='||p_client_id||',
function_id='||p_function_id||',
file_syspk='||p_file_syspk||',
file_format='''||p_file_format||''',
sheet_mnemonic='''||p_sheet_mnemonic||'''';

perform mmt_staging2.fn_jobctrl_block_end(__file_syspk,'FTHLG_TRS_SPEC_Block'); 



/*inserting data into block -FTHLG_TRS_Engine_RPM_Block*/


perform mmt_staging2.fn_jobctrl_block_begin(__client_id,__function_id,__file_syspk,
'FTHLG_TRS_Engine_RPM_Block',__file_format,__sheet_mnemonic,3); 
v_block:='FTHLG_TRS_Engine_RPM_Block';

insert into  mmt_staging2.FTHLG_TRS_Engine_RPM_Block
(
dummy_f,
Tractor_model, 
Tractor_make,
Low_Idle,
High_Idle,
Rated_RPM,
Engine_to_PTO_Ratio_540_PTO,
Engine_to_PTO_Ratio_540E_PTO
)
SELECT *
FROM   crosstab(
       'SELECT  unnest(''{column3,column4,column5,column6,column7}''::text[]) AS col
             , row_number() OVER ()
             , unnest(ARRAY[column3::text,column4::text,column5::text,column6::text,column7::text]) AS val
        FROM   mmt_staging2.stg_process_table_fthlg_trs where rank_tag=''FTHLG_TRS_Engine_RPM''
  or (rank_tag=''FTHLG_TRS_SPEC'' and rank in (1,2))
        ORDER  BY generate_series(1,15),2'
   ) t (col text,a_1 text,a_2 text,a_3 text,a_4 text,a_5 text,a_6 text,a_7 text);


delete from  mmt_staging2.FTHLG_TRS_Engine_RPM_Block where dummy_f is null ;
execute 'update mmt_staging2.FTHLG_TRS_Engine_RPM_Block set 
client_id='||p_client_id||',
function_id='||p_function_id||',
file_syspk='||p_file_syspk||',
file_format='''||p_file_format||''',
sheet_mnemonic='''||p_sheet_mnemonic||'''';


perform mmt_staging2.fn_jobctrl_block_end(__file_syspk,'FTHLG_TRS_Engine_RPM_Block'); 


/*inserting data into block -FTHLG_TRS_Trailer_Block*/


perform mmt_staging2.fn_jobctrl_block_begin(__client_id,__function_id,__file_syspk,
'FTHLG_TRS_Trailer_Block',__file_format,__sheet_mnemonic,4);
v_block:='FTHLG_TRS_Trailer_Block';

insert into mmt_staging2.FTHLG_TRS_Trailer_Block
(
dummy_f,
Type_Of_Trailer,
No_Of_Axle,
No_Of_Wheels,
Trailer_hitch_Height_above_ground_level_mm,
Make_model_of_trailer,
Trailer_platform_length_mm,
Trailer_platform_Width_mm,
Trailer_platform_Height_mm,
Tire_size,
Inflation_pressure_psi,
Track_width_of_trailer_mm,
Horizontal_distance_of_hitch_point_from_trailer_front_face_mm,
Tractor_Rear_Wheel_Center_to_Hitch_Point_Center_Distance_mm,
Distance_from_Trailerfront_axle_distance_from_hitch_point_mm,
Distance_from_tractor_rear_wheel_center_to_tractor_rear_wheel_center_mm,
Trailer_empty_weight_Kg,
Trailer_Gross_Weight_Kg
)
SELECT *
FROM   crosstab(
       'SELECT  unnest(''{column3,column4,column5,column6}''::text[]) AS col
             , row_number() OVER ()
             , unnest(ARRAY[column3::text,column4::text,column5::text,column6::text]) AS val
        FROM   mmt_staging2.stg_process_table_fthlg_trs where rank_tag=''FTHLG_TRS_Trailer'' and rank <=17
        ORDER  BY generate_series(1,15),rank,2'
   ) t ( col text,a_1 text,a_2 text,a_3 text,a_4 text,a_5 text,a_6 text,a_7 text,a_8 text,a_9 text
  ,a_10 text,a_11 text,a_12 text,a_13 text,a_14 text,a_15 text,a_16 text,a_17 text);


update mmt_staging2.FTHLG_TRS_Trailer_Block set report_template_no= 
(select column2 from mmt_staging2.stg_process_table_fthlg_trs where rank=18
and rank_tag='FTHLG_TRS_Trailer')where make_model_of_trailer is not null;

update mmt_staging2.FTHLG_TRS_Trailer_Block set report_template_rev_no=
(select column4 from mmt_staging2.stg_process_table_fthlg_trs where rank=18 
and rank_tag='FTHLG_TRS_Trailer')where make_model_of_trailer is not null;


update  mmt_staging2.FTHLG_TRS_Trailer_Block set report_template_rev_date= 
(select column6 from mmt_staging2.stg_process_table_fthlg_trs where rank=18 and 
rank_tag='FTHLG_TRS_Trailer')where make_model_of_trailer is not null;


execute 'update  mmt_staging2.FTHLG_TRS_Trailer_Block set 
client_id='||p_client_id||',
function_id='||p_function_id||',
file_syspk='||p_file_syspk||',
file_format='''||p_file_format||''',
sheet_mnemonic='''||p_sheet_mnemonic||'''';

perform mmt_staging2.fn_jobctrl_block_end(__file_syspk,'FTHLG_TRS_Trailer_Block'); 
v_context := '';
perform  mmt_staging2.mmt_insert_db_error ( __client_id, __function_id, 1001, 'Compegence', __file_syspk ,__file_format,__sheet_mnemonic ,null,'stg2', 'fn_FTHLG_TRS_Block', v_state, v_msg, v_detail, v_hint, v_context,'success');
return v_context;	

EXCEPTION when OTHERS then 
	
GET STACKED DIAGNOSTICS 
       v_state   = returned_sqlstate,
       v_msg     = message_text,
       v_detail  = pg_exception_detail,
       v_hint    = pg_exception_hint,
       v_context = pg_exception_context;

   	   perform  mmt_staging2.mmt_insert_db_error ( __client_id, __function_id, 1001, 'Compegence', __file_syspk ,__file_format,__sheet_mnemonic ,v_block,'stg2', 'fn_FTHLG_TRS_Block', v_state, v_msg, v_detail, v_hint, v_context,'error');
return v_context;
end
$$ LANGUAGE plpgsql;



