[LIB-13] Add PGN format classes
[chesshog-scanner.git] / src / main / java / org / hedgecode / chess / scanner / format / AbstractPGNFormat.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.text.DateFormat;
20 import java.text.SimpleDateFormat;
21 import java.util.Date;
22 import java.util.HashMap;
23 import java.util.Map;
24
25 /**
26  * AbstractPGNFormat
27  *
28  * @author Dmitry Samoshin aka gotty
29  */
30 public abstract class AbstractPGNFormat implements PGNFormat {
31
32     private static final String MOVES_FORMAT = "%s %s";
33
34     private final DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
35     private final DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
36
37     private final Map<PGNTag, String> pgnTags = new HashMap<>();
38
39     private String pgnMoves;
40
41     @Override
42     public void addTag(PGNTag tag, String value) {
43         pgnTags.put(tag, value);
44     }
45
46     public String getTag(PGNTag tag) {
47         return pgnTags.get(tag);
48     }
49
50     @Override
51     public void addMoves(String moves) {
52         pgnMoves = moves;
53     }
54
55     @Override
56     public String formatDate(Date date) {
57         return dateFormat.format(date);
58     }
59
60     @Override
61     public String formatTime(Date time) {
62         return timeFormat.format(time);
63     }
64
65     protected String formatMoves() {
66         return String.format(
67                 MOVES_FORMAT, moves(), result()
68         );
69     }
70
71     protected String formatTagValue(String value) {
72         return value.replaceAll("([\\\\\"])", "\\\\$1");
73     }
74
75     private String moves() {
76         return pgnMoves != null ? pgnMoves : PGNTag.EMPTY;
77     }
78
79     private String result() {
80         String result = pgnTags.get(PGNTag.RESULT);
81         return result != null ? result : PGNTag.RESULT.defaultValue();
82     }
83
84 }