#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Copyright (c) 2018 Wolfgang Rohdewald <wolfgang@rohdewald.de>
# See LICENSE for details.

"""This implements :class:`gpxity.ServerDirectory`."""


from .directory import Directory, Backup

__all__ = ['ServerDirectory']


class ServerDirectory(Directory):

    """Like :class:`Directory` but the track ids are different: Just a number.

    A new id is generated by adding 1 to the highest existing id.

    The symbolic links per YYYY/MM use the title of the track as link name.

    """

    # pylint: disable=abstract-method

    skip_test = True

    def _new_ident(self, _) ->str:
        """Build a unique id for track.

        Returns:
            A new unique id

        """
        try:
            return str(max(int(x) for x in self._list_gpx()) + 1)
        except ValueError:
            return '1'

    def _write_all(self, track) ->str:
        """save full gpx track. If id_in_backend is defined, keep it.

        Returns:
            The new id_in_backend

        """
        new_ident = track.id_in_backend or self._new_ident(track)

        with Backup(track):
            track.id_in_backend = new_ident
            with open(self.gpx_path(new_ident), 'w', encoding='utf-8') as out_file:
                out_file.write(track.to_xml())
            self._set_filetime(track)

        return new_ident
