package com.aip.gateway.api.aip.utils;

import com.microsoft.informationprotection.IStream;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Base64;

@Slf4j
public class AipFileStream implements IStream {

    private InputStream inputStream;
    private OutputStream outputStream;

    public AipFileStream(String fileDataString) {
        byte[] fileData = Base64.getDecoder().decode(fileDataString);
        this.inputStream = new ByteArrayInputStream(fileData);
    }

    @Override
    public long read(byte[] buffer, long position) {
        try {
            inputStream.skip(position);
            return inputStream.read(buffer);
        } catch (IOException e) {
            log.error("read failed. {}", e.getMessage());
            return -1;
        }
    }

    @Override
    public long write(byte[] data) {
        try {
            outputStream.write(data);
            return data.length;
        } catch (IOException e) {
            log.error("write failed. {}", e.getMessage());
            return -1;
        }
    }

    @Override
    public boolean flush() {
        try {
            outputStream.flush();
            return true;
        } catch (IOException e) {
            log.error("flush failed. {}", e.getMessage());
            return false;
        }
    }

    @Override
    public void seek(long position) {
        try {
            inputStream.skip(position);
        } catch (IOException e) {
            log.error("seek failed. {}", e.getMessage());
        }
    }

    @Override
    public boolean canRead() {
        return true;
    }

    @Override
    public boolean canWrite() {
        return false;
    }

    @Override
    public long position() {
        try {
            return inputStream.available();
        } catch (IOException e) {
            log.error("position failed. {}", e.getMessage());
            return -1;
        }
    }

    @Override
    public long size() {
        try {
            return inputStream.available();
        } catch (IOException e) {
            log.error("size failed. {}", e.getMessage());
            return -1;
        }
    }

    @Override
    public void size(long newSize) {
        // Not applicable for input stream
    }
}
