[LIB-9] Set of entities for PGN parsing and formatting
[chesshog.git] / chesshog-format / src / main / java / org / hedgecode / chess / pgn / format / wrap / AbstractWrapper.java
1 /*
2  * Copyright (c) 2018-2020. Developed by Hedgecode.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.hedgecode.chess.pgn.format.wrap;
18
19 import static org.hedgecode.chess.pgn.PGNConstants.*;
20
21 /**
22  * AbstractWrapper
23  *
24  * @author Dmitry Samoshin aka gotty
25  */
26 public abstract class AbstractWrapper implements MovesWrapper {
27
28     protected abstract int length();
29
30     @Override
31     public String wrap(String moves) {
32         StringBuilder sb = new StringBuilder();
33         int startIndex = 0, endIndex = 0;
34         moves = moves.concat(PGN_SPACE);
35         int index = moves.indexOf(PGN_SPACE);
36         while (index >= 0) {
37             if (index - startIndex >= length()) {
38                 sb.append(
39                         moves.substring(startIndex, endIndex)
40                 ).append(PGN_CRLF);
41                 startIndex = endIndex + 1;
42             }
43             endIndex = index;
44             index = moves.indexOf(PGN_SPACE, index + 1);
45         }
46         sb.append(
47                 moves.substring(startIndex)
48         ).append(PGN_CRLF);
49         return sb.toString();
50     }
51
52 }