# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2025 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Module authors:
#   Alexander Zaft <a.zaft@fz-juelich.de>
#
# *****************************************************************************

"""Frappy test suite SEC node."""

import logging
import shutil
import tempfile
from pathlib import Path

from frappy.lib import generalConfig
from frappy.server import Server

from nicos.utils import loggers

from test.utils import secop_port

TEST_CFG = f'''Node('nicos.test.node',
    '',
    'tcp://{secop_port}',
)

Mod('enumvalue',
    'frappy_demo.modules.Switch',
    'switch to test enum values',
    switch_on_time=0.1,
    switch_off_time=0.1,
)
'''

tmpdir = Path(tempfile.mkdtemp(prefix='nicos-frappy-tmp'))
cfgfile = tmpdir / 'cfg'
with cfgfile.open('w', encoding='utf-8') as f:
    f.write(TEST_CFG)

generalConfig.set_default('lazy_number_validation', False)
generalConfig.set_default('legacy_hasiodev', False)
generalConfig.set_default('tolerate_poll_property', False)
generalConfig.set_default('piddir', tmpdir)
generalConfig.set_default('logdir', tmpdir)
generalConfig.set_default('confdir', tmpdir)
generalConfig.init()

log = loggers.NicosLogger('secop')

# show errors on the console
handler = logging.StreamHandler()
handler.setLevel(logging.ERROR)
handler.setFormatter(logging.Formatter('[SECNODE] %(name)s: %(message)s'))
log.addHandler(handler)

try:
    srv = Server('testserver', log, cfgfiles=[cfgfile])
    srv.run()
finally:
    shutil.rmtree(tmpdir, ignore_errors=True)
