1import collections
2from io import StringIO
3
4from pychess.Utils.GameModel import GameModel
5from pychess.Utils.const import WAITING_TO_START, BLACKWON, WHITEWON, DRAW, FISCHERRANDOMCHESS
6from pychess.Utils.logic import getStatus
7from pychess.Variants.fischerandom import FischerandomBoard
8
9from .ChessFile import ChessFile, LoadingError
10
11
12__label__ = _("Simple Chess Position")
13__ending__ = "fen"
14__append__ = True
15
16
17def save(handle, model, position=None, flip=False):
18    """Saves game to file in fen format"""
19    print(position, model.ply, model.lowply)
20    print(model.boards)
21    print("%s" % model.boards[-1 if position is None or len(model.boards) == 1 else position].asFen(),
22          file=handle)
23    output = handle.getvalue() if isinstance(handle, StringIO) else ""
24    handle.close()
25    return output
26
27
28def load(handle):
29    return FenFile(handle)
30
31
32class FenFile(ChessFile):
33    def __init__(self, handle):
34        ChessFile.__init__(self, handle)
35        self.fen_is_string = isinstance(handle, StringIO)
36        rec = collections.defaultdict(str)
37        line = handle.readline().strip()
38        rec["Id"] = 0
39        rec["Offset"] = 0
40        rec["FEN"] = line
41
42        castling = rec["FEN"].split()[2]
43        for letter in castling:
44            if letter.upper() in "ABCDEFGH":
45                rec["Variant"] = FISCHERRANDOMCHESS
46                break
47
48        self.games = [rec, ]
49        self.count = 1
50
51    def loadToModel(self, rec, position, model=None):
52        if not model:
53            model = GameModel()
54
55        if self.fen_is_string:
56            rec = self.games[0]
57
58        if isinstance(rec, dict) and "Variant" in rec:
59            model.variant = FischerandomBoard
60
61        fen = self.games[0]["FEN"]
62        try:
63            board = model.variant(setup=fen)
64            model.tags["FEN"] = fen
65        except SyntaxError as err:
66            board = model.variant()
67            raise LoadingError(
68                _("The game can't be loaded, because of an error parsing FEN"),
69                err.args[0])
70
71        model.boards = [board]
72        model.variations = [model.boards]
73        model.moves = []
74        if model.status == WAITING_TO_START:
75            status, reason = getStatus(model.boards[-1])
76            if status in (BLACKWON, WHITEWON, DRAW):
77                model.status, model.reason = status, reason
78        return model
79