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

"""
CloudLinux control panel API command line interface
"""

import argparse
from clcommon import cpapi
from clcommon.cloutput import prepare_data_json, prepare_attention_json
from clcommon.cpapi import cpapiexceptions


def cpapi_parser():

    parser = argparse.ArgumentParser(description="%(prog)s - CloudLinux control panel API command line interface")
    parser.add_argument('-j', '--json', action='store_true', default=False, help='Output in json format')
    subparsers = parser.add_subparsers(dest='command')

    docroot_parser = subparsers.add_parser('docroot')
    docroot_parser.add_argument('domain', help='Return document root for domain')

    userdomains_parser = subparsers.add_parser('userdomains')
    userdomains_parser.add_argument('userdomains', help='Return domain and document root pairs for control panel user')

    dblogin_cplogin_pairs_parser = subparsers.add_parser("dblogin_cplogin_pairs")
    dblogin_cplogin_pairs_parser.add_argument("--cplogin_lst", nargs="*",
                                  help="Return mapping for this system users")
    dblogin_cplogin_pairs_parser.add_argument("--with_system_users", action="store_true", default=False,
                                  help="Show system users in output")
    return parser


def flat_plain(data, sep=' '):
    return '\n'.join(map(lambda tuple_: sep.join(tuple_), data))


def main():
    parser = cpapi_parser()
    namespace = parser.parse_args()
    output_ = None
    exit_code = 0
    try:
        if namespace.command == 'docroot':
            domain, user = cpapi.docroot(namespace.domain)
            if namespace.json:
                output_ = prepare_data_json({'domain': domain, 'user': user})
            else:
                output_ = domain + ' ' + user
        elif namespace.command == 'userdomains':
            domain_docroot_pairs = cpapi.userdomains(namespace.userdomains)
            if namespace.json:
                data = list(map(lambda (domain, docroot): {'domain': domain, 'docroot': docroot}, domain_docroot_pairs))
                output_ = prepare_data_json(data)
            else:
                output_ = flat_plain(domain_docroot_pairs)
        elif namespace.command == 'dblogin_cplogin_pairs':
            db_mapping = cpapi.dblogin_cplogin_pairs(namespace.cplogin_lst,
                                                     namespace.with_system_users)
            if namespace.json:
                output_ = prepare_data_json(db_mapping)
            else:
                output_ = flat_plain(db_mapping)
    except (cpapiexceptions.NotSupported, cpapiexceptions.NoDomain), e_:
        if namespace.json:
            output_ = prepare_attention_json(str(e_))
        else:
            exit_code = 1
            output_ = 'ERROR: ' + str(e_)
    return output_, exit_code


if __name__ == '__main__':
    import sys
    output_, exit_code = main()
    if output_:
        print output_
    if exit_code:
        sys.exit(exit_code)
