/*
 * LRW.c
 *
 *  Created on: 09-04-2025
 *      Author: 
 *      Pawe Skoczykoda
 */


#include "tdefs.h"
#include "misc.h"
#include "helper.h"


#include "log_wyl.h"

int log_wyl_initlog(void *arguments, void *logic)
{
	struct log_wyl_args *args = (struct log_wyl_args *)arguments;
	struct log_wyl_logic *log = (struct log_wyl_logic *)logic;

	if(set_bit_ptr_struct(args->io.wyl_L1_in,&log->w_L1_in))
		return -1;
	if(set_bit_ptr_struct(args->io.wyl_L2_in,&log->w_L2_in))
		return -1;
	if(set_bit_ptr_struct(args->io.wyl_L3_in,&log->w_L3_in))
		return -1;
	if(set_bit_ptr_struct(args->io.wyl_3f_in,&log->w_3f))
		return -1;
	if(set_bit_ptr_struct(args->io.blok_w_in,&log->blok_w))
		return -1;
		
	if(set_bit_ptr_struct(args->io.wyl_L1_out,&log->w_L1_out))
		return -1;
	if(set_bit_ptr_struct(args->io.wyl_L2_out,&log->w_L2_out))
		return -1;
	if(set_bit_ptr_struct(args->io.wyl_L3_out,&log->w_L3_out))
		return -1;

	log->dobijacz = (args->params.bity & 0x0001)?1:0;
	log->t_limit = (u32)((args->params.t1) * 1000 / LOOP_CYCLE_MS);

	log->we_L1_pop = 0;
	log->we_L2_pop = 0;
	log->we_L3_pop = 0;
	
	log->timer_L1 = 0;
	log->timer_L2 = 0;
	log->timer_L3 = 0;	
	
	return 0;
}

void log_wyl(void *arguments, void *logic)
{
	struct log_wyl_logic *log = (struct log_wyl_logic *)logic;

	u8 we_L1 = check_struct(&log->w_L1_in)?1:0;
	u8 we_L2 = check_struct(&log->w_L2_in)?1:0;
	u8 we_L3 = check_struct(&log->w_L3_in)?1:0;
	u8 we_bl = check_struct(&log->blok_w)?1:0;
	u8 we_3f = check_struct(&log->w_3f)?1:0;
		
	if (we_bl)
	{
		log->we_L1_imp = 0;
		log->we_L2_imp = 0;
		log->we_L3_imp = 0;
		we_L1 = 0;
		we_L2 = 0;
		we_L3 = 0;
	}
	else
	{
		
		if (log->dobijacz)
		{
			if (((log->we_L1_imp || we_L1) && (log->we_L2_imp || we_L2)) ||
				((log->we_L1_imp || we_L1) && (log->we_L3_imp || we_L3)) ||
				((log->we_L3_imp || we_L3) && (log->we_L2_imp || we_L2)))
			{
				we_3f = 1; //dobijacz
			}
		}			
		
		if (we_3f)
		{
			we_L1 = 1;
			we_L2 = 1;
			we_L3 = 1;	
		}
		
		if (!log->we_L1_imp)
		{
			if (we_L1 && !log->we_L1_pop)
			{
				log->we_L1_imp = 1;
			}
		}		
		else
		{
			if (++log->timer_L1 > log->t_limit)
			{
				log->timer_L1 = 0;
				log->we_L1_imp = 0;		
			}
		}
		
		if (!log->we_L2_imp)
		{
			if (we_L2 && !log->we_L2_pop)
			{
				log->we_L2_imp = 1;
			}
		}		
		else
		{
			if (++log->timer_L2 > log->t_limit)
			{
				log->timer_L2 = 0;
				log->we_L2_imp = 0;		
			}
		}	
		
		if (!log->we_L3_imp)
		{
			if (we_L3 && !log->we_L3_pop)
			{
				log->we_L3_imp = 1;
			}
		}		
		else
		{
			if (++log->timer_L3 > log->t_limit)
			{
				log->timer_L3 = 0;
				log->we_L3_imp = 0;		
			}
		}
	}
	
	check_and_set_struct((log->we_L1_imp || we_L1),&log->w_L1_out);
	check_and_set_struct((log->we_L2_imp || we_L2),&log->w_L2_out);
	check_and_set_struct((log->we_L3_imp || we_L3),&log->w_L3_out);
	
	log->we_L1_pop = we_L1;
	log->we_L2_pop = we_L2;
	log->we_L3_pop = we_L3;
	
}



