package ru.bitel.bgbilling.modules.voice.dyn.mediator.rtc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jfree.util.Log;

import ru.bitel.bgbilling.apps.voice.accounting.mediation.AbstractMediator;
import ru.bitel.bgbilling.apps.voice.accounting.mediation.VoiceRecord;
import ru.bitel.bgbilling.apps.voice.accounting.mediation.VoiceRecordProcessor;
import ru.bitel.bgbilling.modules.voice.common.bean.VoiceDevice;
import ru.bitel.bgbilling.modules.voice.common.bean.VoiceDeviceType;
import ru.bitel.bgbilling.modules.voice.common.mediation.Mediator;
import ru.bitel.common.TimeUtils;
import ru.bitel.bgbilling.server.util.Setup;
import ru.bitel.common.ParameterMap;
import ru.bitel.common.Utils;

/**
 * Парсер логов Ростелекома
 * @author kirill
 *
 */
public class RTCMediator
	extends AbstractMediator
	implements Mediator
{
	private final static Logger logger = LogManager.getLogger();
	private final SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyyMM" );
	private VoiceDevice device; 
	
	@Override
    public Object init( Setup setup, int moduleId, VoiceDevice device, VoiceDeviceType deviceType, ParameterMap config )
        throws Exception
    {
        this.device = device;
	    return super.init( setup, moduleId, device, deviceType, config );        
    }

	@Override
	public void readHourDataLog( final VoiceRecordProcessor processor, final Date hour )
		throws Exception
	{
	    LocalDateTime localDateTime = TimeUtils.convertDateToLocalDateTime( hour );
	    if ( !( localDateTime.getDayOfMonth() == 1 && localDateTime.getHour() == 0 ) )
	    {
	        return;
	    }
	    
        String fullPath = device.getLogPath() + File.separator + dateFormat.format( hour );
        
        File dir = new File( fullPath );
        
        for ( File file : dir.listFiles() )
        {
            if ( !file.getName().endsWith( ".csv" ) )
            {
                continue;
            }

            try( BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream( file ) ), 128 * 1024 ); )
            {
    			String line;
    			while( (line = reader.readLine()) != null )
    			{
    			    if ( !Character.isDigit( line.charAt( 0 ) ) )
    			    {
    			        continue;
    			    }
    
    			    String[] params = line.split( ";" );
    
    				if( params.length >= 9 )
    				{
    				    processLine( processor, params );
    				}
    				else
    				{
    					logger.warn( "Skip line: " + line );
    				}
    			}
            }
    	}
	}
	
	@Override
	public void getLogExists( Date month, int[] data )
	{
	    String path = device.getLogPath();
	    
        File rootDir = new File( path );
        if ( !rootDir.exists() )
        {
            return;
        }
                
        File monthDir = new File( path + File.separator + dateFormat.format( month ) );
        
        if ( monthDir == null || !monthDir.exists() )
        {
            return;
        }
        
        if ( monthDir.listFiles().length > 3 )
        {
            for ( int day = 0; day < data.length; day++ )
            {
                data[day] = 0b111111111111111111111111;
            }
        }
	}
	
//	Номер;Дата;Время;Наименование направления;Краткое наименование услуги;Направление;Продолжительность/ доп услуги, мин.;Количество уведомлений/ справок,ед.;Сумма услуг (без НДС), руб.
//	8313090343;01.10.2019;07:57:13;GSM-900/1800 НИЖНИЙ НОВГОРОД;ВНЗ;9601605505;1;0;3.71

	protected void processLine( final VoiceRecordProcessor processor, final String[] params )
		throws InterruptedException
	{
		final VoiceRecord record = processor.next();

		record.e164CallingStationId = "7" + params[0];
        record.callingStationId = params[0];

        record.e164CalledStationId = "7" + params[5];
        record.calledStationId = params[5];
        
        record.sessionStart = TimeUtils.parseDate( params[1] + " " + params[2], TimeUtils.DATE_FORMAT_PATTERN_DDMMYYYY_HHMMSS );
		record.duration = record.connectionDuration = Utils.parseInt( params[6], 0 );
		
//		record.trunkIncoming = params[6];
//		record.trunkOutgoing = params[7];
//		record.category = Utils.parseInt( params[8], 0 );

//		record.connectionDuration = Utils.parseInt( params[9].trim(), 0 );
		try
		{
			record.callCost = new BigDecimal( params[8] );
//			record.callOperCost = new BigDecimal( params[11] );
		}
		catch( Exception e )
		{
		    Log.error( params[8] + " " + e.getMessage() );
		}
	}
}