package turgen.decoder;

import java.io.*;
import turgen.Logger;
import turgen.Turgen;
import turgen.Utils;


public class LowerSilesiaTurbo2000FileDecoder implements FileDecoder,BlockDecoderListener {

    private BlockDecoder blockDecoder;
    private static final String MSG_PFX="[LST2000] ";
    private long firstFileSample=0L;
    private Logger log;

    public boolean decodeFile(String outdir, Logger log, PulseDecoder d,DecoderConfig config) throws Exception {
        
        this.log=log;
        
        
        switch(config.lowerSilesiaTurbo2000FileFormat) {
            case DecoderConfig.PL_LOWER_SILESIA_TURBO_2000_FORMAT_AUTOTURBO : {
                
                blockDecoder = new Turbo2000BlockDecoder(d,config,256,Turbo2000BlockDecoder.PULSE_WIDTHS_LOWER_SILESIA_TURBO_2000);    
                blockDecoder.setBlockDecoderListener(this);
                return decodeAutoTurbo(outdir,d,config);
            }
            case DecoderConfig.PL_LOWER_SILESIA_TURBO_2000_FORMAT_UE_PROTECTED:
            case DecoderConfig.PL_LOWER_SILESIA_TURBO_2000_FORMAT_UE_UNPROTECTED: {
                blockDecoder = new Turbo2000BlockDecoder(d,config,24,Turbo2000BlockDecoder.PULSE_WIDTHS_LOWER_SILESIA_TURBO_2000);    
                blockDecoder.setBlockDecoderListener(this);
                return decodeUnknownExterminator(outdir,d,config);
            }
        }
        
        return false;
        
    }

    String constructFilespec(String outdir, int[] data, int tp,long sample,boolean prependSample,boolean hasName) throws Exception {

        /*First we prepend sample number. We do this always if there is no file name*/
        String nameBase="";
        if (prependSample==true || hasName==false) {
            nameBase+=Utils.padZeros(Long.toString(sample),10);
            nameBase+='_';
        }
        
        if (hasName) {
            /*Then we add polished name taken from the header*/
            nameBase+=Utils.getPolishedFilespec(data, 2, 10);
        }
        else {
            nameBase+="no_name";
        }
        
        
        /*Then we handle output directory*/
        File odf = new File(outdir);
        outdir = odf.getCanonicalPath();
        String retVal;
        
        /*And append file extension*/
        if (outdir.endsWith(Turgen.sp)) {
            retVal = outdir + nameBase + ".xex";
        }
        else {
            retVal = outdir + Turgen.sp + nameBase + ".xex";
        }
        return retVal;
        
    }

    

    private boolean decodeAutoTurbo(String outdir, PulseDecoder d, DecoderConfig config) throws Exception {
        /*Arrays for header and data*/
        int[] header;
        int[] data;
        
        /*Results of decoding*/
        BlockDecodeResult bdr;
        int errCode;
        
        /*Try to decode header*/
        while (true) {

            /*Decode 19 bytes block*/
            firstFileSample=d.getCurrentSample();
            
            bdr = blockDecoder.decodeBlock(19);
            errCode=bdr.getErrorCode();

            /*Immediate break ?*/
            if (BlockDecodeResult.isCodeImmediateBreak(errCode)) {
                log.addMessage(MSG_PFX+bdr.getFullErrorMessage(),true);
                return false;
            }

            /*Block physically OK*/
            if (BlockDecodeResult.isCodeOK(errCode)) {
                /*Check whether it seems to be Lower silesiau Turbo 2000 header. If true, break
                  the headerDecode loop*/
                if (bdr.getData()[0]==0) break;
            }

        }

        /*Header was decoded*/
        header=bdr.getData();
        
        /*Write header to the log*/
        log.addMessage(MSG_PFX+"HEADER: "+Utils.t2kHeaderToString(header)+" <"+bdr.getFullErrorMessage()+">",true);
        
        /*Check if file type is supported*/
        /*
        if (header[1]!=4) {
            log.addMessage(MSG_PFX+"File type "+Integer.toString(header[1])+" not supported",true);
            return true;
        }*/
        
        /*Obtain file size from the header*/
        int size = header[14] + header[15] * 256;
        
        /*Add two bytes - check sum and indentification byte*/
        size += 2;

        /*Decode data block*/
        bdr=blockDecoder.decodeBlock(size);
        errCode=bdr.getErrorCode();

        /*Immediate break ?*/
        if (BlockDecodeResult.isCodeImmediateBreak(errCode)) {
             log.addMessage(MSG_PFX+bdr.getFullErrorMessage(),true);
             return false;
        }

        /*Block physically or logically bad*/
        if (BlockDecodeResult.isCodePhysicalError(errCode)) {
            log.addMessage(MSG_PFX+bdr.getFullErrorMessage(),true);
            return true;
        }

        /*Data block was decoded correctly*/
        data=bdr.getData();

        /*Check the first byte of the block*/
        if (data[0]!=255) {
            log.addMessage(MSG_PFX+"ERROR: First byte of data is not 255",true);
            return true;
        }

        /*Construct file specifier from the header*/
        String fspec = constructFilespec(outdir, header, header[1], firstFileSample,config.genPrependSampleNumber,true);
        
        File f = new File(fspec);
        f.delete();

        /*Flush output*/
        FileOutputStream fos;
        BufferedOutputStream bos=null;

        try {

            fos = new FileOutputStream(fspec);
            bos = new BufferedOutputStream(fos);
            
            for (int i = 1; i < size - 1; i++) {
                bos.write(data[i]);
            }

            /*Finish file operation*/
            bos.flush();
            bos.close();
        } catch (IOException e) {
            log.addMessage(MSG_PFX + Utils.getExceptionMessage(e), true);
            try {
                if (bos!=null) bos.close();
            } catch (IOException xe) {
                xe.printStackTrace();
            }
            return true;
        }

        log.addMessage(MSG_PFX+"SAVE: " + fspec + " <"+bdr.getFullErrorMessage()+">",true);
        return true;
        
        
    }

    private boolean decodeUnknownExterminator(String outdir, PulseDecoder d, DecoderConfig config) throws Exception {
        
        BlockDecodeResult bdr;
        int errorCode;
        
        int[] dummyRunSegment;
        int[] segmentHeader;
        
        if (config.lowerSilesiaTurbo2000FileFormat == DecoderConfig.PL_LOWER_SILESIA_TURBO_2000_FORMAT_UE_PROTECTED) {
            /*Try to decode dummy RUN segment*/
            while (true) {
                firstFileSample = d.getCurrentSample();
                bdr = blockDecoder.decodeBlock(3);
                errorCode = bdr.getErrorCode();

                /*Immediate break ?*/
                if (BlockDecodeResult.isCodeImmediateBreak(errorCode)) {
                    log.addMessage(MSG_PFX + bdr.getFullErrorMessage(), true);
                    return false;
                }

                /*Is block phyisically and logically OK?*/
                if (BlockDecodeResult.isCodeOK(errorCode)) {
                    dummyRunSegment = bdr.getData();
                    if (dummyRunSegment[0] == 0xE0 && dummyRunSegment[1] == 0x02) {
                        break;
                    }
                }
            }

            /*Dummy run segment decoded OK*/
            log.addMessage(MSG_PFX + "Initial dummy RUN segment header found <" + bdr.getFullErrorMessage() + ">", true);
        }
        
        
        /*Keep reading segment header and segment data pairs*/
        FileDataCache cache = new FileDataCache(16384);
        cache.add(255);
        cache.add(255);
        
        while(true) {
            
            /*Read segment header*/
            bdr = blockDecoder.decodeBlock(5);
            errorCode = bdr.getErrorCode();
            
            /*Immediate break ?*/
            if (BlockDecodeResult.isCodeImmediateBreak(errorCode)) {
                log.addMessage(MSG_PFX+bdr.getFullErrorMessage(),true);
                return false;
            }
            
            /*Any other error*/
            if (!BlockDecodeResult.isCodeOK(errorCode)) {
                log.addMessage(MSG_PFX+"ERROR: Segment header block not found or corrupt<"+bdr.getFullErrorMessage()+">", true);
                return true;
            }
            
            /*Check validity of the segment header*/
            segmentHeader = bdr.getData();
            int firstAddr = segmentHeader[0]+segmentHeader[1]*256;
            int lastAddr = segmentHeader[2]+segmentHeader[3]*256;
            
            /*Is that termination segment header*/
            if (firstAddr == 0 && lastAddr == 0) {
                break;
            }
            
            /*Is that valid segment header*/
            if (lastAddr<firstAddr) {
                log.addMessage(MSG_PFX+"ERROR: Segment header block corrupt - negative segment size  <"+bdr.getFullErrorMessage()+">", true);
                return true;
            }
            
            /*Place segment header to the cache*/
            cache.add(segmentHeader,4);
            if (config.lowerSilesiaTurbo2000Verbose==true) {
                log.addMessage(MSG_PFX+"Segment header: "+Integer.toString(firstAddr)+"-"+Integer.toString(lastAddr)+" <"+bdr.getFullErrorMessage()+">",true);
            }
            
            /*Read segment data*/
            bdr = blockDecoder.decodeBlock(lastAddr-firstAddr+1+1);
            errorCode = bdr.getErrorCode();
            
            /*Immediate break ?*/
            if (BlockDecodeResult.isCodeImmediateBreak(errorCode)) {
                log.addMessage(MSG_PFX+bdr.getFullErrorMessage(),true);
                return false;
            }
            
            /*Any other error*/
            if (!BlockDecodeResult.isCodeOK(errorCode)) {
                log.addMessage(MSG_PFX+"ERROR: Segment data block not found or corrupt <"+bdr.getFullErrorMessage()+">", true);
                return true;
            }
            
            /*Place segment data to the cache*/
            cache.add(bdr.getData(),bdr.getData().length-1);
            if (config.lowerSilesiaTurbo2000Verbose==true) {
                log.addMessage(MSG_PFX+"Segment data: "+Integer.toString(bdr.getData().length)+" bytes <"+bdr.getFullErrorMessage()+">",true);
            }
            
        }
        
        String fspec = constructFilespec(outdir, null, 0, firstFileSample, config.genPrependSampleNumber, false);
        
        /*Decoding finished - save binary file*/
        FileOutputStream fos;
        BufferedOutputStream bos=null;
        
        int[] data = cache.getBytes();
        
        try {

            fos = new FileOutputStream(fspec);
            bos = new BufferedOutputStream(fos);
            
            for (int i = 0; i < data.length; i++) {
                bos.write(data[i]);
            }

            /*Finish file operation*/
            bos.flush();
            bos.close();
        } catch (IOException e) {
            log.addMessage(MSG_PFX + Utils.getExceptionMessage(e), true);
            try {
                if (bos!=null) bos.close();
            } catch (IOException xe) {
                xe.printStackTrace();
            }
            return true;
        }

        log.addMessage(MSG_PFX+"SAVE: " + fspec + " <"+bdr.getFullErrorMessage()+">",true);
        return true;
        
        
    }
    
    public void blockDecodeEvent(Object eventInfo) {
        log.impulse(true);
    }

    
}
