package com.brilliance.mda.runtime.mda.impl;

import com.brilliance.mda.runtime.mda.IStream;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.io.*;
import java.util.Arrays;

public class StreamImpl extends DataGrid implements IStream,Serializable {

    transient ByteArrayOutputStream bos = new ByteArrayOutputStream();
    private String name;
    private String type;
    private String value;


    @JsonIgnore
    public InputStream getInputStream()
    {
        return new ByteArrayInputStream(this.bos.toByteArray());
    }

    @JsonIgnore
    public OutputStream getOutputStream()
    {
        return this.bos;
    }
    public boolean isEmpty()
    {
        for (String row : getRows()) {
            if (!row.trim().isEmpty()){
                return false;
            }
        }
        return true;
    }

    @JsonIgnore
    public String getValue()
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < rows.size(); i++) {
            sb.append(rows.get(i));
            if(i<rows.size() - 1)
                sb.append("\r\n");
        }
        return sb.toString();
    }

    @JsonIgnore
    public Class getDataType()
    {
        return String.class;
    }

    @JsonIgnore
    public String getName()
    {
        return this.name;
    }

    @JsonIgnore
    public void setName(String name)
    {
        this.name = name;
    }
    @JsonIgnore
    public String getType()
    {
        return this.type;
    }
    @JsonIgnore
    public void setType(String type)
    {
        this.type = type;
    }

    public long size()
    {
        return this.bos.size();
    }

    public void close()
    {
        this.bos.reset();
        this.clearLines();
    }

    public String setValue(String value)
    {
        this.value = value;
        if(value != null && value.length() > 0){
            Arrays.stream(value.split("\r\n")).forEach(rows::add);
        }
        return value;
    }

    public String toString(){
        return this.getValue();
    }
}
