[LIB-13] Add PGN format classes
[chesshog-scanner.git] / src / main / java / org / hedgecode / chess / scanner / format / TypeMovesFormat.java
1 /*
2  * Copyright (c) 2019-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.scanner.format;
18
19 import java.util.Arrays;
20
21 import static org.hedgecode.chess.scanner.format.PGNConstants.*;
22
23 /**
24  * TypeMovesFormat
25  *
26  * @author Dmitry Samoshin aka gotty
27  */
28 public enum TypeMovesFormat {
29
30     LINE ( new LineMovesFormat() ),
31     WRAP ( new WrapMovesFormat() );
32
33     private MovesFormat movesFormat;
34
35     TypeMovesFormat(MovesFormat movesFormat) {
36         this.movesFormat = movesFormat;
37     }
38
39     public String format(Move[] moves) {
40         return movesFormat.format(moves);
41     }
42
43     static class LineMovesFormat extends WrapMovesFormat {
44
45         LineMovesFormat() {
46             super(PGN_MAX_LINE_LENGTH);
47         }
48
49     }
50
51     static class WrapMovesFormat implements MovesFormat {
52
53         private int lineLength;
54
55         WrapMovesFormat() {
56             this(PGN_DEF_LINE_LENGTH);
57         }
58
59         WrapMovesFormat(int length) {
60             lineLength = length;
61         }
62
63         @Override
64         public String format(Move[] moves) {
65             Arrays.sort(moves);
66             int maxLength = lineLength - PGN_CRLF.length();
67             int length = 0;
68             StringBuilder sb = new StringBuilder();
69             for (Move move : moves) {
70                 String nextMove = move.ply() % 2 != 0
71                         ? String.format(WHITE_MOVE_FORMAT, move.ply() / 2 + 1, move.move())
72                         : String.format(BLACK_MOVE_FORMAT, move.move());
73                 if (length + nextMove.length() > maxLength) {
74                     sb.append(PGN_CRLF);
75                     length = 0;
76                 }
77                 sb.append(nextMove);
78                 length += nextMove.length();
79             }
80             return sb.toString().trim();
81         }
82
83     }
84
85 }