# (c) Copyright 2014-2016 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging

from freezerclient import base
from freezerclient import exceptions
from freezerclient import utils


logging = logging.getLogger(__name__)


def format_action(action):
    column = (
        'Action ID',
        'Name',
        'Action',
        'Mode',
        'Path to Backup or Restore',
        'Storage',
        'Snapshot',
        'Container',
        'Log_file',
        'Remove_older_than',
        'Max_retries_interval',
        'Max_retries',
        'User_id',
        'Project_id'
    )

    data = (
        action.get('action_id'),
        action.get('freezer_action', {}).get('backup_name', ''),
        action.get('freezer_action', {}).get('action', 'backup'),
        action.get('freezer_action', {}).get('mode', 'fs'),
        action.get('freezer_action', {}).get('path_to_backup', ''),
        action.get('freezer_action', {}).get('storage', 'swift'),
        action.get('freezer_action', {}).get('snapshot', 'False'),
        action.get('freezer_action', {}).get('container', ''),
        action.get('freezer_action', {}).get('log_file', ''),
        action.get('freezer_action', {}).get('remove_older_than', '365'),
        action.get('max_retries_interval', '6'),
        action.get('max_retries', '5'),
        action.get('user_id', ''),
        action.get('project_id', ''),
    )
    return column, data


class ActionShow(base.FreezerShowOne):
    """Show a single action """
    def get_parser(self, prog_name):
        parser = super(ActionShow, self).get_parser(prog_name)
        parser.add_argument(dest='action_id',
                            help='ID of the action')
        return parser

    def take_action(self, parsed_args):
        action = self.client.actions.get(parsed_args.action_id)

        if not action:
            raise exceptions.ApiClientException('Action not found')

        return format_action(action)


class ActionList(base.FreezerLister):
    """List all actions for your user"""
    def get_parser(self, prog_name):
        parser = super(ActionList, self).get_parser(prog_name)

        parser.add_argument(
            '--limit',
            dest='limit',
            default=100,
            help='Specify a limit for search query',
        )

        parser.add_argument(
            '--offset',
            dest='offset',
            default=0,
            help='',
        )

        parser.add_argument(
            '--search',
            dest='search',
            default='',
            help='Define a filter for the query',
        )
        return parser

    def take_action(self, parsed_args):
        search = utils.prepare_search(parsed_args.search)

        actions = self.client.actions.list(
            limit=parsed_args.limit,
            offset=parsed_args.offset,
            search=search
        )

        columns = ('Action ID', 'Name', 'Action',
                   'Path to Backup or Restore', 'Mode', 'Storage', 'snapshot')

        # Print empty table if no actions found
        if not actions:
            actions = [{}]
            data = ((action.get('action-id', ''),
                     action.get('freezer_action', {}).get('backup_name', ''),
                     action.get('freezer_action', {}).get('action', ''),
                     action.get('freezer_action', {}).get(
                         'path_to_backup', ''),
                     action.get('freezer_action', {}).get('mode', ''),
                     action.get('freezer_action', {}).get('storage', ''),
                     action.get('freezer_action', {}).get('snapshot', '')
                     ) for action in actions)
        else:
            data = ((action.get('action_id'),
                     action.get('freezer_action', {}).get('backup_name', ''),
                     action.get('freezer_action', {}).get('action', 'backup'),
                     action.get('freezer_action', {}).get(
                         'path_to_backup', ''),
                     action.get('freezer_action', {}).get('mode', 'fs'),
                     action.get('freezer_action', {}).get('storage', 'swift'),
                     action.get('freezer_action', {}).get('snapshot', 'False')
                     ) for action in actions)

        return columns, data


class ActionDelete(base.FreezerCommand):
    """Delete an action from the api"""
    def get_parser(self, prog_name):
        parser = super(ActionDelete, self).get_parser(prog_name)
        parser.add_argument(dest='action_id',
                            help='ID of the action')
        return parser

    def take_action(self, parsed_args):
        self.client.actions.delete(parsed_args.action_id)


class ActionCreate(base.FreezerShowOne):
    """Create an action from a file"""
    def get_parser(self, prog_name):
        parser = super(ActionCreate, self).get_parser(prog_name)
        parser.add_argument('--file',
                            dest='file',
                            required=True,
                            help='Path to json file with the action')
        return parser

    def take_action(self, parsed_args):
        action_data = utils.doc_from_json_file(parsed_args.file)
        action_id = self.client.actions.create(action_data)
        action = self.client.actions.get(action_id)
        if not action:
            raise exceptions.ApiClientException('Action created but not found')
        return format_action(action)


class ActionUpdate(base.FreezerShowOne):
    """Update an action from a file"""
    def get_parser(self, prog_name):
        parser = super(ActionUpdate, self).get_parser(prog_name)
        parser.add_argument(dest='action_id',
                            help='ID of the session')

        parser.add_argument(dest='file',
                            help='Path to json file with the action')
        return parser

    def take_action(self, parsed_args):
        action_data = utils.doc_from_json_file(parsed_args.file)
        self.client.actions.update(parsed_args.action_id, action_data)
        action = self.client.actions.get(parsed_args.action_id)
        if not action:
            raise exceptions.ApiClientException('Action not found')
        return format_action(action)
