package ru.bitel.bgbilling.modules.tv.dyn.lfstrm;

import bitel.billing.server.util.Config;
import ru.bitel.bgbilling.common.BGException;
import ru.bitel.bgbilling.kernel.event.EventListener;
import ru.bitel.bgbilling.kernel.event.EventListenerContext;
import ru.bitel.bgbilling.kernel.event.common.Event;
import ru.bitel.bgbilling.modules.tv.common.event.TvAccountModifyEvent;
import ru.bitel.bgbilling.server.util.Setup;
import ru.bitel.common.ParameterMap;
import ru.bitel.common.Utils;

public class LifeStreamEventListener
	implements EventListener<Event>
{
	public static class Conf
		extends Config
	{
		final boolean accountLoginEmailCheck;

		public Conf( int mid, ParameterMap moduleSetup, Setup serverSetup )
		{
			super( mid, moduleSetup, serverSetup );

			accountLoginEmailCheck = moduleSetup.getInt( "account.login.email.check", 0 ) > 0;
		}
	}

	@Override
	public void notify( Event e, EventListenerContext ctx )
		throws BGException
	{
		if( e instanceof TvAccountModifyEvent )
		{
			tvAccountModifyEvent( ctx, (TvAccountModifyEvent)e );
		}
	}

	private void tvAccountModifyEvent( EventListenerContext ctx, TvAccountModifyEvent e )
	{
		if( e.getNewTvAccount() == null || e.getNewTvAccount().getParentId() > 0 )
		{
			return;
		}

		final int moduleId = e.getModuleId();

		final Conf conf = ctx.getSetup().getConfig( moduleId, Conf.class );

		if( conf.accountLoginEmailCheck )
		{
			if( !Utils.checkEmail( e.getNewTvAccount().getLogin() ) )
			{
				e.setError( "В поле логин должен быть указан корректный E-mail." );
			}
		}
	}
}
