/*
 * Copyright 2017 Yoshiyuki Takemori
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.imakaramegane.soniccsv;

import java.io.Reader;

import com.imakaramegane.soniccsv.internal.CsvReaderDefaultImpl;
import com.imakaramegane.soniccsv.internal.RecordEndRule;
import com.imakaramegane.soniccsv.internal.RecordEndRuleStandards;
import com.imakaramegane.soniccsv.internal.RecordEndRuleOneChar;
import com.imakaramegane.soniccsv.internal.RecordEndRuleTwoChars;

/**
 * @author Yoshiyuki Takemori
 */
public class CsvReaderFactory {

    public static CsvReader create( Reader source ) {
        return create( new CsvPreference(), source );
    }

    public static CsvReader create( CsvPreference prefs, Reader source ) {
        return new CsvReaderDefaultImpl( prefs, source,
                createRecordEndRule( prefs ) );
    }

    private static RecordEndRule createRecordEndRule( CsvPreference prefs ) {
        switch( prefs.getLineBreakSequence() ) {
        case CR:
            return new RecordEndRuleOneChar( '\r' );
        case LF:
            return new RecordEndRuleOneChar( '\n' );
        case CRLF:
            return new RecordEndRuleTwoChars( '\r', '\n' );
        case SYSTEM:
            return createRecordEndRuleSytem();
        default: // ALL:
            return new RecordEndRuleStandards();
        }
    }

    private static RecordEndRule createRecordEndRuleSytem() {
        final char[] lineSep = System.getProperty( "line.separator" )
                .toCharArray();
        if( lineSep.length == 1 ) {
            return new RecordEndRuleOneChar( lineSep[0] );
        } else if( lineSep.length == 2 ) {
            return new RecordEndRuleTwoChars( lineSep[0], lineSep[1] );
        } else {
            throw new RuntimeException( "Unsupported line.separator - "
                    + System.getProperty( "line.separator" ) );
        }
    }
}
