/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package textkeymatcher.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.Charset;
import textkeymatcher.entity.LineData;

/**
 *
 * @author seraphy
 */
public class LineDataLoader {
    
    
    public interface LineDataLoaderCallback {
        
        void fetch(LineData line);
        
    }
    
    private LineDataLoaderCallback callback;
    
    private LineDataBuilder builder;

    public LineDataLoader(LineDataBuilder builder, LineDataLoaderCallback callback) {
        if (callback == null || builder == null) {
            throw new IllegalArgumentException();
        }
        this.callback = callback;
        this.builder = builder;
    }
    
    public void load(Reader rd) throws IOException {
        if (rd == null) {
            throw new IllegalArgumentException();
        }
        BufferedReader br = new BufferedReader(rd);
        try {
            String line;
            while ((line = br.readLine()) != null) {
                LineData lineData = builder.parse(line);
                callback.fetch(lineData);
            }
            
        } finally {
            br.close();
        }
    }
    
    public void load(InputStream is, Charset cs) throws IOException {
        if (is == null || cs == null) {
            throw new IllegalArgumentException();
        }
        InputStreamReader rd = new InputStreamReader(is, cs);
        try {
            load(rd);

        } finally {
            rd.close();
        }
    }
    
    public void load(File file, Charset cs) throws IOException {
        if (file == null || cs == null) {
            throw new IllegalArgumentException();
        }
        InputStream is = new FileInputStream(file);
        try {
            load(is, cs);

        } finally {
            is.close();
        }
    }
    
    public void load(String text) {
        if (text == null) {
            text = "";
        }
        StringReader sr = new StringReader(text);
        try {
            try {
                load(sr);
                
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }

        } finally {
            sr.close();
        }
    }
    
}
