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

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

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

/**
 * Медиатор m200. Берет из папки inbox файлы вида *.log
 */
public class M200Mediator
    extends AbstractMediator
    implements Mediator
{
    protected VoiceRecord processLine( final VoiceRecordProcessor processor, final String[] params )
        throws InterruptedException
    {
        CDR cdr = new CDR();
        cdr.amount = Utils.parseInt( params[3], 0 );
        if ( skipCDR( cdr ) )
        {
            return null;
        }
        
        // 0                       1               2       3       4       5      
        // 2024-01-01T00:01:45     32938810        8928    0       C335401 C000000

        VoiceRecord record = processor.next();
        record.sessionStart = TimeUtils.convertLocalDateTimeToDate( LocalDateTime.parse( params[0] ) );        
        record.callingStationId = params[1].replaceAll( "[^0-9]*", "" );
        record.e164CallingStationId = callingStationIdToE164( record.callingStationId );
        record.calledStationId = params[2].replaceAll( "[^0-9]*", "" );
        record.e164CalledStationId = calledStationIdToE164( record.calledStationId );
        record.duration = record.connectionDuration = Utils.parseInt( params[3], 0 );
        record.trunkIncoming = params[4];
        record.trunkOutgoing = params[5];
        record.category = 0;
        
        return record;
    }
    
    protected void parseLog( Path path, Map<String, List<String>> cdrs )
    {
        if ( Files.exists( path ) )
        {
            try
            {
                LocalDateTime now = LocalDateTime.now();
                int defYear = now.getYear() - 2000;
                int defMonth = now.getMonthValue();
                int defDayOfMonth = now.getDayOfMonth();
                int defHour = now.getHour();
                int defMinute = now.getMinute();
                int defSecond = now.getSecond();
                
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHH");
                
                for ( String line : Files.readAllLines( path ) )
                {
                	logger.debug( "line = {}", line );

                	String[] params = line.split( " " );
                    
                    CDR cdr = new CDR();

                    // 0       1          2      3       4          5      6        7        8 9 10
                    // C355402 4932565638 932543 C255704 4932565638 932543 16-01-24 00:33:34 8 6 16
                    // C365830 9203601731 939399 C355609 9203601731 939399 16-01-24 00:35:09 178 171 16
                    
                    if ( params.length < 11 )
                    {
                        continue;
                    }

                    String ansCode =  params[10];
                    
                    // отбрасывать можно звонки с кодом ответа 1
                    if ( ansCode.equals( "1" ) || ansCode.equals( "27" ) || ansCode.equals( "34" ) ||  ansCode.equals( "134" ))
                    {
                    	continue;
                    }
                    
                    cdr.trunkIncoming = params[0];
                    cdr.numberA = params[1];
                    cdr.numberB = params[2];
                    
                    cdr.trunkOutgoing = params[3];
                    cdr.origNumberA = params[4];
                    
                    int year = 2000 + Utils.parseInt( params[6].substring( 6 ), defYear );
                    int month = Utils.parseInt( params[6].substring( 3, 5 ), defMonth );
                    int dayOfMonth = Utils.parseInt( params[6].substring( 0, 2 ), defDayOfMonth );
                    int hour = Utils.parseInt( params[7].substring( 0, 2 ), defHour );
                    int minute = Utils.parseInt( params[7].substring( 3, 5 ), defMinute );
                    int second = Utils.parseInt( params[7].substring( 6 ), defSecond );
                    cdr.start = LocalDateTime.of( year, month, dayOfMonth, hour, minute, second );

                    cdr.amount = Utils.parseInt( params[9], 0 );
                    
                    String date = cdr.start.format( formatter );
                    List<String> buffer = cdrs.get( date );
                    if ( buffer == null )
                    {
                        buffer = new ArrayList<>();
                        cdrs.put( date, buffer );
                    }
                    buffer.add( cdr.toString() );
                    if ( logger.isDebugEnabled() )
                    {
                        logger.debug( "cdr => {}", cdr.toString() );
                    }
                }
            }
            catch( Exception ex )
            {
                logger.error( ex );
            }
        }        
    }
    
    protected boolean filterFiles( Path file )
    {
        if ( !file.getFileName().toString().endsWith( ".log" ) )
        {
            return true;
        }
        return false;
    }
    
    protected Path getOutboxPath( Path processedDir, Path file )
    {
    	//smp_01_01_2024.log
    	String mmyyyy = file.getFileName().toString().replaceAll( "^[^\\d]+\\d{2}_(\\d{2})_(\\d{4})\\.log$", "$1$2" );    	
        return Paths.get( processedDir.toString(), mmyyyy.substring( 2 ), mmyyyy.substring( 0, 2 ) );
    }
}
