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

import argparse
import json
import os
import re
import requests
import tempfile

from saas.library.python.sandbox import SandboxApi
from saas.tools.devops.lib23.ask_for_user_action import ask_yes_or_no
from saas.tools.devops.lib23.nanny_helpers import NannyService

FERRYMAN_CONFIG_NAME = 'config.pb.txt'
FERRYMAN_CONFIG_RESOURCE_TYPE = 'FERRYMAN_CONFIG'


def fetch_nanny_static_config(service):
    config = ''
    history = NannyService(service).history_runtime_attrs
    for snapshot in history:
        files = snapshot['content']['resources']['static_files']
        for static_file in files:
            if static_file['local_path'] == FERRYMAN_CONFIG_NAME:
                config = static_file['content']
                break
        if config:
            break

    return config


def fetch_nanny_resource_config(service):
    runtime_attributes = NannyService(service).runtime_attrs
    resources = runtime_attributes['resources']['sandbox_files']
    resource_id = ''
    config = ''
    for resource in resources:
        if resource['resource_type'] == FERRYMAN_CONFIG_RESOURCE_TYPE:
            resource_id = resource['resource_id']
            break
    if resource_id:
        sandbox_api = SandboxApi()
        config_resource = sandbox_api.resource_by_id(resource_id)
        url = config_resource.content_http_url
        config = requests.get(url).content
    return config


def fetch_sandbox_config(service):
    sandbox_api = SandboxApi()
    ferryman_name_regexp = re.compile(r'saas_(ferryman|fm)_(?P<name>\w.*)')
    ferryman_name = ferryman_name_regexp.match(service).group('name')
    resources = sandbox_api.find_resources(resource_type=FERRYMAN_CONFIG_RESOURCE_TYPE, state='READY',
                                           attrs={'service': ferryman_name}, limit=1)
    if resources:
        resource = resources[0]
        url = resource.content_http_url
        config = requests.get(url).content
        resource_info = resource.nanny_resource_info()
    return config, resource_info


def print_diff(static_config, resource_config):
    tmp_static_config = tempfile.NamedTemporaryFile(prefix='static_config')
    tmp_static_config.write(static_config)
    tmp_static_config.flush()

    tmp_resource_config = tempfile.NamedTemporaryFile(prefix='resource_config')
    tmp_resource_config.write(resource_config)
    tmp_resource_config.flush()

    os.system("vimdiff {} {}".format(tmp_static_config.name, tmp_resource_config.name))


def get_opts():
    parser = argparse.ArgumentParser(description='Fetch ferryman configs')
    parser.add_argument('-s', '--service', help='service name', required=True)
    parser.add_argument('-r', '--release_type', help='resource release type', required=False, default='stable')
    return parser.parse_args()


def main():
    args = get_opts()
    service = args.service
    release_type = args.release_type

    static_config = fetch_nanny_static_config(service)
    print('Static config')
    print(json.dumps(static_config, indent=2))
    nanny_resource_config = fetch_nanny_resource_config(service)
    if nanny_resource_config:
        print('Sandbox resource config committed to service')
        print(json.dumps(nanny_resource_config, indent=2))
        if ask_yes_or_no("Do you want to see the diff for config.pb.txt (left is nanny static file, right is sandbox resource)?"):
            print_diff(static_config, nanny_resource_config)
    else:
        sandbox_config, resource_info = fetch_sandbox_config(service)
        print('Sandbox resource config (not committed yet)')
        print(json.dumps(sandbox_config, indent=2))
        if ask_yes_or_no("Do you want to see the diff for config.pb.txt (left is nanny static file, right is sandbox resource)?"):
            print_diff(static_config, sandbox_config)
        if ask_yes_or_no("Do you want to add resource to nanny service?"):
            nanny_service = NannyService(service)
            print('Removing static config')
            nanny_service.remove_resource(FERRYMAN_CONFIG_NAME)
            print('Adding sandbox resource')
            nanny_service.add_sandbox_file(local_path=FERRYMAN_CONFIG_NAME, sandbox_resource_info=resource_info)
            ferryman_name = re.compile(r'saas_(ferryman|fm)_(?P<name>\w.*)').match(service).group('name')
            print('Configure ticket integration (service {})'.format(ferryman_name))
            nanny_service.add_ticket_integration_rule(
                sandbox_task_type=resource_info['task_type'],
                sandbox_resource_type=resource_info['resource_type'],
                filter_expression='sandbox_release.release_type == \'{}\' and \'{}\' == sandbox_release.title'.format(
                    release_type, 'Ferryman config for' + ferryman_name),
                desc='Ferryman configs')


if __name__ == "__main__":
    main()
