#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright (c) 2016 Thorsten Simons (sw@snomis.de)
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Sos of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyrighftware without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copiet notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

import sys
import time
import configparser
from os.path import expanduser

from .init import AWS_REGIONS, TEMPLATE

# the tags used in the configuration file
tags = ['comment', 'endpoint', 'region', 'https', 'aws_access_key_id',
        'aws_secret_access_key']
# these tags are not allowed to be empty
noblanktags = ['https', 'aws_access_key_id', 'aws_secret_access_key']
# these are bool tags
booltags = ['https']


def readconf():
    '''
    Read the configuration file, parse it and return a dict.

    :return:    a dict containing the various profiles
    '''
    confp = configparser.ConfigParser()
    if not confp.read([expanduser('~/.hs3sh.conf'), '.hs3sh.conf']):
        createtemplateconf()
        sys.exit()

    profs = {}
    errors = 0

    for p in confp.sections():
        profs[p] = {}
        for t in tags:
            # check for AWS region correctness
            if t == 'region':
                if (confp.get(p, t, fallback='') and
                    confp.get(p, t, fallback='') not in AWS_REGIONS):
                    errors += 1
                    print('.hs3sh.conf: [{}]/{}: invalid region'
                          .format(p,t), flush=True)

            # check for tags that shall not be empty
            elif t in  noblanktags:
                if not confp.get(p, t, fallback=''):
                    errors += 1
                    print('.hs3sh.conf: [{}]/{}: empty'
                          .format(p,t), flush=True)

            # make sure if an endpoint is set, no region is set
            elif t == 'endpoint':
                if (not confp.get(p, t, fallback='') and
                        not confp.get(p, 'region', fallback='')):
                    errors += 1
                    print('.hs3sh.conf: [{}]/{}: not set requires a region set'
                          .format(p,t), flush=True)
                elif (confp.get(p, t, fallback='') and
                        confp.get(p, 'region', fallback='')):
                    errors += 1
                    print('.hs3sh.conf: [{}]/{}: must not have a region set'
                          .format(p,t), flush=True)

            profs[p][t] = confp.get(p, t, fallback=None) \
                if t not in booltags else confp.getboolean(p, t, fallback=True)

    if errors:
        time.sleep(.5)
        raise ValueError('parsing .hs3sh.conf showed {} errors - please check...'
                         .format(errors))

    return profs

def createtemplateconf():
    '''Ask the user if a template config file shall be created and do so...'''
    print('No configuration file (.hs3sh.conf) found.')
    answer = input('Do you want me to create a template file (y/n)? ')

    if answer in ['y', 'Y']:
        try:
            with open('.hs3sh.conf', 'w') as outhdl:
                for l in TEMPLATE:
                    print(l, file=outhdl)
        except Exception as e:
            sys.exit('fatal: failed to created template file...\n    hint: {}'
                     .format(e))
        else:
            print('\nA template file (.hs3sh.conf) has been created in the '
                  'current directory.')
            print('For best security, move it to you home directory and make\n'
                  'sure no other user can access it (chmod 600 ~/.hs3sh.conf).')
            print('Then edit it to fit your needs...')
            print()
