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 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.common.TimeUtils;
import ru.bitel.common.Utils;

/**
 * Парсер логов Ростелекома
 * @author kirill
 *
 */
public class RTCMediator
	extends AbstractMediator
{
	private final SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyyMM" );
	
	@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
    				{
    				    getLogger().warn( "Skip line: " + line );
    				}
    			}
            }
    	}
	}
	
    //	Номер;Дата;Время;Наименование направления;Краткое наименование услуги;Направление;Продолжительность/ доп услуги, мин.;Количество уведомлений/ справок,ед.;Сумма услуг (без НДС), руб.
    //	8313090343;01.10.2019;07:57:13;GSM-900/1800 НИЖНИЙ НОВГОРОД;ВНЗ;9601605505;1;0;3.71
	protected VoiceRecord processLine( final VoiceRecordProcessor processor, final String[] params )
		throws InterruptedException
	{
		VoiceRecord record = processor.next();
        record.sessionStart = TimeUtils.parseDate( params[1] + " " + params[2], TimeUtils.DATE_FORMAT_PATTERN_DDMMYYYY_HHMMSS );
        record.duration = record.connectionDuration = Utils.parseInt( params[6], 0 );
        record.callingStationId = params[0].replaceAll( "[^0-9]*", "" );
		record.e164CallingStationId = callingStationIdToE164( record.callingStationId );
        record.calledStationId = params[5].replaceAll( "[^0-9]*", "" );
        record.e164CalledStationId = calledStationIdToE164( record.calledStationId );
		
		try
		{
			record.callCost = new BigDecimal( params[8] );
		}
		catch( Exception e )
		{
		    getLogger().error( params[8] + " " + e.getMessage() );
		}
		return record;
	}
}