# -*- coding:utf-8 -*-
"""
Function: get_screen_shot.py moudle. This moudle mainly involves the capturing
 and Downloading the System Screen Image on the Service Side function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2020-2021
"""
import os
import sys
from scripts import common_function


def getscreenshot_init(parser, parser_list):
    """

    Args:
              parser            : major command argparser
              parser_list       : save subcommand parser list
    Returns:
         getscreenshot
    Raises:
        None
    Examples:
         None
    Date:  2020.4.16
    """
    sub_parser = parser.add_parser('getscreenshot',
                                   help='''capture screenshot''')
    sub_parser.add_argument('-F', dest='file',
                            required=False,
                            help='the local path and file name '
                                 'of download file,'
                                 'file extensions should be ".jpeg"')

    parser_list['getscreenshot'] = sub_parser

    return 'getscreenshot'


def _resptaskparse(resp, client):
    """
    parse response code and body
    Args:
              resp            (dic): task reponse information
              client               : RedfishClient object
    Returns:
         None
    Raises:
        None
    Examples:
         None
    Date:  2020.4.16
    """
    taskid = resp['resource']['@odata.id']

    add_resp = client.get_resource(taskid)
    try:
        if add_resp['status_code'] != 200:
            message_dict = add_resp.get('message', {}).get('error', {})
            message_str = message_dict['@Message.ExtendedInfo'][0]['Message']
            message = message_str.lower()
            print('Failure: ' + message[:-1])
        else:
            message = add_resp['resource'].get('Messages', {}).get('Message', '').lower()
            print('Failure: ' + message[:-1])
    except (AttributeError, TypeError, IndexError):
        print('Failure: The task request response status code is %s' % str(
            add_resp['status_code']))
    sys.exit(144)


def _respparse(resp):
    """
    parse response code and body
    Args:
              resp            (dic):   reponse information
    Returns:
         None
    Raises:
        None
    Examples:
         None
    Date:  2020.4.16
    """
    msgs = resp.get('message', {}).get('error', {}).get('@Message.ExtendedInfo', {})
    print('Failure: %s' % (common_function.change_message(msgs[0]['Message'])))


def check_parameter(parser, args):
    """
    Function Description:check CLI command
    Parameter:args object:CLI command
    parser object:subcommand ArgumentParser object
    """
    if args.file is not None:
        if os.path.splitext(args.file)[-1] != ".jpeg":
            parser.error('Failure: The format of the file is incorrect. '
                         'The file extension should be jpeg')


def getscreenshot(client, args):
    """
    capture screen shot
    Args:
              client                 : RedfishClient object
              parser                 : subcommand argparser
              args                   : parameter list
    Returns:
         resp
    Raises:
        None
    Examples:
         None
    Date:  2020.4.15
    """
    slotid = client.get_slotid()
    if slotid is None:
        return None

    payload = {}
    url = "/redfish/v1/Managers/%s/DiagnosticService/" \
          "Actions/DiagnosticService.CaptureScreenShot" \
          % slotid
    resp = client.create_resource(url, payload)
    if resp is None:
        return None

    if resp['status_code'] == 202:
        resp_task = client.print_task_prog(resp, 5, flag="getscreenshot")
        if resp_task is None:
            return None
        if resp_task == 'Exception':
            _resptaskparse(resp, client)
        if resp_task == 'Completed':
            file_path = "/tmp/web/manualscreen.jpeg"
            if args.file is not None:
                common_function.export_local_path(client, slotid, file_path,
                                                  args)
            print('Success: successfully completed request\n')
    else:
        _respparse(resp)

    return resp
