# -*- coding: utf-8 -*-
import logging
import itertools

from chibi_atlas import Chibi_atlas


logger = logging.getLogger( "chibi_sshd.snippets" )


def from_string( content ):
    lines = content.split( "\n" )
    lines = map( str.strip, lines )
    lines = filter( bool, lines )
    lines = itertools.filterfalse( line_is_comment, lines )
    return Chibi_atlas( dict( map( parse_line, lines ) ) )


def to_string( content ):
    return "\n".join( ( to_line( k, v ) for k, v in content.items() ) )


def line_is_comment( line ):
    return line.startswith( "#" )


def parse_line( line ):
    k, v = line.split( maxsplit=1 )
    if '#' in v:
        v, trash = v.split( "#", 1 )
    k = k.strip()
    v = v.strip()
    if v == 'no':
        v = False
    elif v == 'yes':
        v = True
    if k == 'AllowUsers':
        v = v.split()
    return k, v


def to_line( k, v ):
    if isinstance( v, bool ):
        if v:
            v = 'yes'
        else:
            v = 'no'
    if k == 'AllowUsers':
        if isinstance( v, list ):
            v = " ".join( v )
        elif isinstance( v, str ):
            v = v
        else:
            raise NotImplementedError(
                "no esta implementado que AllowUsers sea de "
                f"tipo {type(v)} con el valor de '{v}'"
            )
    return f"{k} {v}"
