# -*- coding: utf-8 -*-
import json
import os
import flask
import logging
import logging.handlers

import backend.yt_cypress
import backend.models
import backend.startrek_issues as si
import backend.resources_calculation as rcalc
import backend.manage_requests as mr
import backend.shooting as sht

from saas.library.python.sandbox import SchedulerStatus
from saas.tools.ssm.modules.misc import load_and_write_resources, collect_users_from_string, load_resources
from saas.tools.devops.lib23 import findkey as fk

from backend.passport import passport_required
from backend.forms import service_form, namespace_form, shooting_form, findkey_form
from backend.helpers import BlueprintsHelpers
from flask import request, render_template, current_app, send_from_directory, escape, render_template_string

load_and_write_resources('/conf')
load_and_write_resources('/static')

ssm_viewer_page = flask.Blueprint('ssm_viewer', __name__)
yt_client = backend.yt_cypress.SaaSYtJobControl()


@ssm_viewer_page.route('/static/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(os.getcwd(), 'static'),
                               'favicon.ico', mimetype='image/vnd.microsoft.icon')


@ssm_viewer_page.route('/static/logo')
def logo():
    return send_from_directory(os.path.join(os.getcwd(), 'static'),
                               'vonny.jpg', mimetype='image/vnd.microsoft.icon')


@ssm_viewer_page.route('/', methods=['GET', 'POST'])
@ssm_viewer_page.route('/add', methods=['GET', 'POST'])
@passport_required
def new_service():
    login = BlueprintsHelpers.get_user_login(request)
    data = ''
    if current_app.debug:
        app_mode = 'prestable'
    else:
        app_mode = 'prod'
    testing_form = service_form.TestingServiceForm(request.form)
    prestable_form = service_form.PrestableServiceForm(request.form)
    production_form = service_form.ProductionServiceForm(request.form)
    return render_template('new.html', title=u'Создание сервиса', testing_form=testing_form, prestable_form=prestable_form,
                           production_form=production_form,  data=data, ssm_type=app_mode,
                           front_hostname=BlueprintsHelpers.get_front_hostname(), yandex_login=login,
                           admin_mode=BlueprintsHelpers.is_saas_admin(login))


@ssm_viewer_page.route('/namespaces', methods=['GET', 'POST'])
@passport_required
def new_namespace():
    login = BlueprintsHelpers.get_user_login(request)
    data = ''
    if current_app.debug:
        app_mode = 'prestable'
    else:
        app_mode = 'prod'
    ns_form = namespace_form.NamespaceForm(request.form)
    return render_template('new_namespace.html', title=u'Создание неймспейса', namespace_form=ns_form,  data=data, ssm_type=app_mode,
                           front_hostname=BlueprintsHelpers.get_front_hostname(), yandex_login=login, admin_mode=BlueprintsHelpers.is_saas_admin(login))


@ssm_viewer_page.route('/findkey', methods=['GET', 'POST'])
@passport_required
def findkey():
    login = BlueprintsHelpers.get_user_login(request)
    form = findkey_form.FindkeyForm(request.form)
    form.user_login.data = login
    if request.method == "POST":
        answer = {}
        if form.validate():
            arguments = form.data
            for key in arguments:
                if isinstance(arguments[key], list) and len(arguments[key]) == 1:
                    arguments[key] = arguments[key][0]
            arguments['is_kv'] = (arguments['kv_or_ft'] == "kv")
            arguments['is_full_text'] = (arguments['kv_or_ft'] == "ft")
            arguments['ignore_dc'] = [dc for dc in arguments['ignore_dc'].replace(' ', '').split(',')]
            for el in ['kps', 'src_tvm_id', 'dst_tvm_id', 'yql_day_count']:
                arguments[el] = int(arguments[el]) if arguments[el] != '' else None
            logging.info("Call findkey with arguments {}".format(arguments))
            try:
                response, string = fk.main(return_string=True, console=False, colored=False, **arguments)
            except Exception as e:
                answer['error'] = str(e)
                return json.dumps(answer)
            answer['findkey_data'] = render_template('findkey_templates.html', response=response,
                                                     front_hostname=BlueprintsHelpers.get_front_hostname(),
                                                     yandex_login=login, admin_mode=BlueprintsHelpers.is_saas_admin(login))
        answer['form_errors'] = form.errors
        return json.dumps(answer)
    return render_template('findkey.html', title=u'Findkey', front_hostname=BlueprintsHelpers.get_front_hostname(),
                           yandex_login=login, admin_mode=BlueprintsHelpers.is_saas_admin(login), findkey_form=form)


@ssm_viewer_page.route('/request', methods=['POST'])
@passport_required
def service_request():
    startrek_ticket = ''
    task = ''
    login = BlueprintsHelpers.get_user_login(request)
    request_type = request.form.get('request_type')
    form = create_form_by_data(request)
    form.user_login.data = login

    # Check valid return errors or OK
    if form.validate():
        if 'namespace' in request_type:
            request_data = prepare_namespace_request_data(form)
            startrek_ticket = create_namespace_request(request_data, user=login)
        elif 'shooting' in request_type:
            if 'regular' in request_type:
                task = sht.schedule(form)
            else:
                task = sht.shoot_to_saas_service(form)
        else:
            request_data = prepare_service_request_data(form, rtype=request_type)
            startrek_ticket = create_service_request(request_data, rtype=request_type, user=login)

    answer = {'form_errors': form.errors}
    if startrek_ticket:
        answer['ticket'] = startrek_ticket
    elif task:
        answer['task'] = task
    else:
        answer['error'] = 'Создание заявки не удалось. Обратитесь в чат saas-duty или к saku@'
    return json.dumps(answer)


@ssm_viewer_page.route('/shoot_to_service', methods=['GET', "POST"])
@passport_required
def shoot_to_service():
    login = BlueprintsHelpers.get_user_login(request)
    regular_form = shooting_form.RegularShootingForm(request.form)
    if request.method == "POST":
        answer = {}
        shooting_table, shootings_list, shooting_rps = sht.load_table()
        answer['shooting_table'] = render_template_string(sht.get_macro_from_html(dict(load_resources("/jinja/macro.html"))[''].replace('\n', ''), 'render_shooting_table'),
                                                          title='Нагрузочное тестирование',
                                                          table=zip(shooting_table, shootings_list, shooting_rps),
                                                          front_hostname=BlueprintsHelpers.get_front_hostname(),
                                                          yandex_login=login,
                                                          admin_mode=BlueprintsHelpers.is_saas_admin(login))
        return json.dumps(answer)

    if request.args.get('mode'):
        mode = request.args.get('mode')
    else:
        mode = 'table'
    if mode == 'form':
        loaded = sht.load_form(request.args.get('request_id'))
        regular_form = shooting_form.RegularShootingForm(**loaded)

    return render_template('shoot_to_service.html', title='Нагрузочное тестирование',
                           custom_form=shooting_form.CustomShootingForm(),
                           regular_form=regular_form,
                           front_hostname=BlueprintsHelpers.get_front_hostname(), yandex_login=login,
                           admin_mode=BlueprintsHelpers.is_saas_admin(login), mode=mode)


@ssm_viewer_page.route('/update_shooting', methods=['POST'])
@passport_required
def update_shooting():
    request_args = request.get_json(force=True)
    request_action = request_args.get('action')
    request_id = request_args.get('request_id')

    if not (request_id and request_action):
        return json.dumps({'status': False})

    sch = sht.sandbox_api.scheduler_by_id(request_id)
    if request_action == 'turn_shooting':
        if sch.status == SchedulerStatus.STOPPED:
            sch.start()
        else:
            sch.stop()
        return json.dumps({'status': True})
    elif request_action == 'delete_shooting':
        sht.sandbox_api.delete_scheduler(sch.id)
        ticket_id = sht.name_value_search(sch['task']['custom_fields'], 'ticket')
        if ticket_id is not None:
            if ticket_id is not None and 'SAASLOADTEST' in ticket_id:
                sht.close_issue(ticket_id)
        return json.dumps({'status': True})
    elif request_action == 'iterrupt_current':
        pass
    else:
        return json.dumps({'status': False})


@ssm_viewer_page.route('/update_request', methods=['POST'])
@passport_required
def update_request():
    login = BlueprintsHelpers.get_user_login(request)
    request_id = request.form.get('request_id')
    request_type = request.form.get('request_type')
    form = create_form_by_data(request)
    form.user_login.data = login

    # Check valid return errors or OK
    if form.validate():
        job_attrs = yt_client.get_job_info(request_id)
        issue_num = job_attrs['sla_info'].get('ticket')

        if request_type == 'namespace':
            request_data = prepare_namespace_request_data(form)
            issue_change_data = si.prepare_issue_data(request_data)
            issue_comment_body = si.startrek_client._prepare_namespace_body(request_data['namespace_name'], request_data['ferryman_service'],
                                                                            request_data['ferryman_ctype'],
                                                                            owners_list=issue_change_data['owners_list'],
                                                                            namespace_size=issue_change_data['namespace_size'],
                                                                            namespace_doccount=issue_change_data['namespace_doccount'],
                                                                            comment=issue_change_data['comment'])
        else:
            request_data = prepare_service_request_data(form, rtype=request_type)
            instances_count = request_data['instances_count']/request_data['replicas_per_dc']
            issue_change_data = si.prepare_issue_data(request_data)
            issue_comment_body = si.startrek_client._prepare_issue_body(request_data['service_name'], request_data['service_ctype'],
                                                                        request_data['service_type'],
                                                                        instances_count=instances_count,
                                                                        other_data=issue_change_data)
        for key in request_data:
            if key in job_attrs and request_data[key]:
                job_attrs[key] = request_data[key]
        logging.info(job_attrs)
        job_attrs['sla_info']['ticket'] = issue_num
        logging.info(job_attrs)
        yt_client._remove_lock(request_id)
        yt_client._set_job_attrs(request_id, job_attrs)
        si.startrek_client.add_comment(issue_num, 'Параметры заявки были изменены:\n' + issue_comment_body)
    answer = {'data': form.data,
              'form_errors': form.errors}
    return json.dumps(answer)


@ssm_viewer_page.route('/requests', methods=['GET', 'POST'])
@passport_required
def admin_requests():
    login = BlueprintsHelpers.get_user_login(request)
    requests = {}
    jobs = yt_client.get_avail_jobs()
    for job in jobs:
        job_info = yt_client.get_job_info(job)
        requests[job] = {
            'job_info': job_info,
            'job_form': prepare_form_by_data(job_info),
            'job_status': get_job_status(job_info),
            'job_ticket': job_info['sla_info']['ticket']
        }
    return render_template('requests.html', title=u'Заявки', yandex_login=login, requests=requests,
                           admin_mode=BlueprintsHelpers.is_saas_admin(login), front_hostname=BlueprintsHelpers.get_front_hostname())


@ssm_viewer_page.route('/change_request', methods=['POST'])
@passport_required
def service_request_action():
    login = BlueprintsHelpers.get_user_login(request)
    request_args = request.get_json(force=True)
    request_action = request_args.get('action')
    request_id = request_args.get('request_id')
    if not (request_id and request_action):
        return json.dumps({'status': False})
    if request_action == 'approve':
        mr.confirm_request(login, request_id)
    if request_action == 'cancel_approve':
        mr.umconfirm_request(login, request_id)
    elif request_action == 'start':
        mr.start_request(login, request_id)
    elif request_action == 'stop':
        mr.stop_request(login, request_id)
    elif request_action == 'discard':
        mr.discard_request(login, request_id)
    return json.dumps({'status': True})


@ssm_viewer_page.route('/get_request_status', methods=['GET', 'POST'])
@passport_required
def get_request_status():
    request_args = request.get_json(force=True)
    request_id = request_args.get('request_id')
    if not request_id:
        return json.dumps({'error': 'Заявки {} не найдено'.format(request_id)})
    job_info = yt_client.get_job_info(request_id)
    try:
        job_status = get_job_status(job_info)
    except KeyError:
        return json.dumps({'error': 'Заявка {} возможно была выполнена или удалена'.format(escape(request_id))})
    return job_status


@ssm_viewer_page.route('/calculate_resources', methods=['GET', 'POST'])
@passport_required
def calc_resources():
    answer = {}

    request_args = request.get_json(force=True)
    search_rps = request_args.get('search_rps')
    service_type = request_args.get('service_type')
    index_size = request_args.get('index_size')
    delivery_type = request_args.get('delivery_type')

    if search_rps.isdigit() and service_type and index_size and delivery_type:
        search_rps = int(search_rps)
        index_size = convert_count_from_char(index_size, 'bytes')
        if service_type == 'search':
            answer['required_resources'] = rcalc.calc_resources_for_search(search_rps, index_size, delivery_type)
        elif service_type == 'kv':
            answer['required_resources'] = rcalc.calc_resources_for_kv(search_rps, index_size, delivery_type)
    else:
        answer['error'] = 'Необходимо корректно заполнить поля SLA для расчета ресурсов'
    return json.dumps(answer)


@ssm_viewer_page.route('/quota_used', methods=['GET'])
@passport_required
def show_services_quotas():
    """
    Get service quotas table and prepare data for render
    """
    login = BlueprintsHelpers.get_user_login(request)
    service_quotas_data = backend.models.AbcServiceQuota.load_all_quotas()  # type: List[AbcServiceQuota]

    rendered_template = render_template(
        'quota_usage.html',
        title=u'Квоты сервисов',
        front_hostname=BlueprintsHelpers.get_front_hostname(),
        service_quotas_data=service_quotas_data,
        yandex_login=login,
        admin_mode=BlueprintsHelpers.is_saas_admin(login),
    )
    return rendered_template


def get_job_status(job_info):
    if job_info['approved']:
        if job_info['status']['job'] == 'NEW':
            job_info['status']['job'] = 'APPROVED'
    else:
        job_info['status']['job'] = 'NEED_APPROVE'

    return job_info['status']


def create_form_by_data(request_data):
    request_type = request_data.form.get('request_type')
    if request_type == 'namespace':
        form = namespace_form.NamespaceForm(request_data.form)
    elif request_type == 'prestable':
        form = service_form.PrestableServiceForm(request_data.form)
    elif request_type == 'testing':
        form = service_form.TestingServiceForm(request_data.form)
    elif request_type == 'production':
        form = service_form.ProductionServiceForm(request_data.form)
    elif request_type == 'custom_shooting':
        form = shooting_form.CustomShootingForm(request_data.form)
    elif request_type == 'regular_shooting':
        form = shooting_form.RegularShootingForm(request_data.form)
    else:
        logging.error("Unknown request_type %s in request_data %s", request_type, request_data)
        raise Exception("Unknown request_type")
    return form


def create_namespace_request(data, user=None):
    """
    Create namespace request:
    1) Create Startrek issue
    2) Create yt job
    :param data: type dict
    :param user: type str
    :return: type str
    """
    job_name = 'ns-' + data['ferryman_service'] + '-' + data['namespace_name']
    # All communal services has ctype stable_middle_kv
    logging.info(data)
    if not yt_client.check_job_exists(job_name):
        ticket_num = si.startrek_create_namespace_ticket(data, user=user)
        data['sla_info']['ticket'] = ticket_num
        if ticket_num:
            si.startrek_approve_comment(ticket_num, data, 'namespace')
            yt_client.new_namespace_job(data['namespace_name'], data['ferryman_service'], data['ferryman_ctype'], owners=data['owners_list'],
                                        size=data['namespace_size'], doccount=data['namespace_doccount'], ticket=ticket_num)
            return ticket_num
        else:
            job_data = yt_client.get_job_info(job_name)
            return job_data['sla_info'].get('ticket')
    else:
        job_info = yt_client.get_job_info(job_name)
        if job_info:
            return job_info['sla_info'].get('ticket')


def create_service_request(data, rtype='production', user=None):
    """
    Create service request:
    1) Create Startrek issue
    2) Create yt job
    Returns Startrek issue num
    :param data: type dict
    :param rtype: type str
    :param user: type str
    :return: type str
    """
    job_name = data['service_ctype'] + '-' + data['service_name']
    logging.info(data)
    if not yt_client.check_job_exists(job_name):
        ticket_num = si.startrek_create_service_ticket(data, user=user)
        data['sla_info']['ticket'] = ticket_num
        if ticket_num:
            si.startrek_approve_comment(ticket_num, data, rtype)
            if data['service_ctype'] != 'testing':
                try:
                    services_quotas_data = rcalc.get_quotas_data()
                    si.startrek_quota_report(ticket_num, services_quotas_data, data)
                except Exception as exc:
                    logging.exception(exc)
            yt_client.new_service_job(data['service_name'], data['service_ctype'], data['service_type'],
                                      data['instances_count'],
                                      req_memory=data.get('req_memory', 10), replicas_per_dc=data.get('replicas_per_dc', 1),
                                      sla_info=data['sla_info'], delivery_info=data['delivery_info'], req_cpu=data.get('req_cpu', 1),
                                      no_indexing=data.get('no_indexing'), startrek_issue=True, allocation_type=data.get('allocation_type', 'yp'),
                                      template_service=data.get('template_service'), service_tvm=data.get('service_tvm'),
                                      service_saas_tvm=data.get('service_saas_tvm', False))
            # Finally tickets structure
            if data['service_ctype'] != 'testing':
                if not data.get('service_tvm'):
                    ticket_num_sec = si.startrek_create_sec_ticket(data, user=user)
                else:
                    ticket_num_sec = None
                if 'prestable' not in data['service_ctype'] :
                    ticket_production_num = si.startrek_create_service_production_ticket(data, user=user)
                    ticket_num_perf = si.startrek_create_perf_ticket(data, user=user)
                    si.startrek_client.make_depends_link(ticket_production_num, ticket_num)
                    si.startrek_client.make_depends_link(ticket_production_num, ticket_num_perf)
                    if ticket_num_sec:
                        si.startrek_client.make_depends_link(ticket_production_num, ticket_num_sec)
                elif ticket_num_sec:
                    si.startrek_client.make_depends_link(ticket_num, ticket_num_sec)
            return data['sla_info']['ticket']
        else:
            job_data = yt_client.get_job_info(job_name)
            return job_data['sla_info'].get('ticket')
    else:
        job_info = yt_client.get_job_info(job_name)
        if job_info:
            return job_info['sla_info'].get('ticket')


def split_count_string(string):
    for i, c in enumerate(string):
        if not c.isdigit():
            return string[:i], string[i:]


def convert_count_from_char(count, char_type):
    """
    Calculate count from string
    :param count:  type str
    :param char_type:  type str in ['decimal', 'bytes']
    :return: type int
    """
    result = ''

    if count.isdigit():
        result = int(count)
    else:
        digit, substr = split_count_string(count)
        substr = substr.strip().lower()
        digit = int(digit)
        if char_type == 'decimal':
            if substr in ['k']:
                result = digit * 10**3
            elif substr in ['m']:
                result = digit * 10**6
            elif substr in ['b']:
                result = digit * 10**9
        elif char_type == 'bytes':
            if substr in ['kb', 'k']:
                result = digit * 2**10
            elif substr in ['mb', 'm']:
                result = digit * 2**20
            elif substr in ['gb', 'g']:
                result = digit * 2**30
            elif substr in ['tb', 't']:
                result = digit * 2**40
    return result


def prepare_namespace_request_data(form):
    """
    Collect request data from form for creating namespace request
    :param form: type wtforms form
    :return: type dict
    """
    data = dict()
    data['sla_info'] = {}
    data['delivery_info'] = {}

    if form.namespace_name.data:
        data['namespace_name'] = form.namespace_name.data.strip()
    if form.owners_list.data:
        data['owners_list'] = collect_users_from_string(form.owners_list.data)
    if form.ferryman_service.data:
        data['ferryman_service'] = form.ferryman_service.data
    if form.ferryman_ctype.data:
        data['ferryman_ctype'] = form.ferryman_ctype.data
    if form.namespace_size.data:
        data['namespace_size'] = convert_count_from_char(form.namespace_size.data, 'bytes')
    if form.namespace_doccount.data:
        data['namespace_doccount'] = convert_count_from_char(form.namespace_doccount.data, 'decimal')
    if form.comment.data:
        data['comment'] = form.comment.data
    return data


def prepare_service_request_data(form, rtype='production'):
    """
    Collect request data from form for creating service request
    :param form: type wtforms form
    :param rtype: type str
    :return: type dict
    """
    data = dict()
    data['sla_info'] = {}
    data['delivery_info'] = {}

    # Basic info
    if form.service_name.data:
        data['service_name'] = form.service_name.data.strip()
    if form.service_type.data:
        data['service_type'] = form.service_type.data

    if rtype == 'testing':
        # add _t suffix for testing service name
        if not data['service_name'].endswith('_t'):
            data['service_name'] += '_t'
        data['service_ctype'] = 'testing'
    else:
        data['service_ctype'] = form.service_ctype.data

    # SAAS-5594
    if 'dj' in data['service_type']:
        data['template_service'] = 'template_dj'

    if form.replicas_per_dc.data:
        data['replicas_per_dc'] = form.replicas_per_dc.data

    if form.instances_count.data and form.replicas_per_dc.data:
        data['instances_count'] = int(form.instances_count.data) * int(form.replicas_per_dc.data)

    if rtype == 'production':
        if form.cpu_requirements.data:
            data['req_cpu'] = form.cpu_requirements.data
        if form.memory_requirements.data:
            data['req_memory'] = form.memory_requirements.data

    # Delivery info
    if rtype != 'testing':
        data['delivery_info']['delivery_type'] = form.delivery_type.data
        data['delivery_info']['delivery_type_value'] = dict(form.delivery_type.choices).get(form.delivery_type.data)
        if form.yt_cluster.data:
            data['delivery_info']['yt_cluster'] = form.yt_cluster.data
        if form.yt_ferryman_format.data:
            data['delivery_info']['yt_ferryman_format'] = form.yt_ferryman_format.data
        if form.logbroker_tvm_id.data:
            data['delivery_info']['logbroker_tvm_id'] = form.logbroker_tvm_id.data
        if data['delivery_info']['delivery_type'] == 'logbroker' and form.logbroker_traffic_volume.data:
            data['delivery_info']['logbroker_traffic_volume'] = form.logbroker_traffic_volume.data

    # Security info
    if rtype != 'testing':
        if form.service_tvm.data:
            data['service_tvm'] = form.service_tvm.data
            if form.service_saas_tvm.data:
                data['service_saas_tvm'] = form.service_saas_tvm.data

    # SLA info
    if form.abc_user_service.data:
        data['sla_info']['abc_user_service'] = form.abc_user_service.data
    if form.abc_quota_service.data:
        data['sla_info']['abc_quota_service'] = form.abc_quota_service.data

    if form.owners_list.data:
        data['sla_info']['owners'] = collect_users_from_string(form.owners_list.data)
        data['sla_info']['responsibles'] = data['sla_info']['owners']

    if rtype == 'production':
        if form.search_rps.data:
            data['sla_info']['search_rps'] = convert_count_from_char(form.search_rps.data, 'decimal')
        if form.index_size.data:
            data['sla_info']['total_index_size_bytes'] = convert_count_from_char(form.index_size.data, 'bytes')
        if form.maxdocs.data:
            data['sla_info']['maxdocs'] = convert_count_from_char(form.maxdocs.data, 'decimal')
        if form.search_q_99_ms.data:
            data['sla_info']['search_q_99_ms'] = form.search_q_99_ms.data
        if form.search_q_999_ms.data:
            data['sla_info']['search_q_999_ms'] = form.search_q_999_ms.data

    if data['delivery_info'].get('delivery_type') and 'snapshot' in data['delivery_info']['delivery_type']:
        data['no_indexing'] = True
    else:
        data['no_indexing'] = False

    if form.comment.data:
        data['comment'] = form.comment.data
    return data


def prepare_form_by_data(data):
    # Create form
    if 'job_type' in data and data['job_type'] == 'namespace':
        job_type = 'namespace'
    else:
        job_type = 'service'
    if job_type == 'namespace':
        form = namespace_form.NamespaceForm()
    else:
        if data['service_ctype'] == 'testing':
            form = service_form.TestingServiceForm()
        elif 'prestable' in data['service_ctype']:
            form = service_form.PrestableServiceForm()
        else:
            form = service_form.ProductionServiceForm()
    if job_type == 'namespace':
        form.namespace_name.data = data['namespace_name']
        form.ferryman_service.data = data['ferryman_service']
        form.ferryman_ctype = data['ferryman_ctype']
        if 'owners_list' in data:
            form.owners_list.data = ','.join(data['owners_list'])
        if 'namespace_size' in data:
            form.namespace_size.data = data['namespace_size']
        if 'namespace_doccount' in data:
            form.namespace_doccount.data = data['namespace_doccount']
    elif job_type == 'service':
        # Common attrs
        form.service_name.data = data['service_name']
        form.abc_user_service.data = data['sla_info'].get('abc_user_service')
        form.abc_quota_service.data = data['sla_info'].get('abc_quota_service')
        form.owners_list.data = ','.join(data['sla_info'].get('owners', []))
        form.service_type.data = data['service_type']
        if data.get('replicas_per_dc'):
            form.instances_count.data = int(data['instances_count']) / int(data['replicas_per_dc'])
        else:
            form.instances_count.data = data['instances_count']
        form.replicas_per_dc.data = data['replicas_per_dc']
        if data['service_ctype'] != 'testing':
            form.delivery_type.data = data['delivery_info'].get('delivery_type')
            form.yt_cluster.data = data['delivery_info'].get('yt_cluster')
            form.yt_ferryman_format.data = data['delivery_info'].get('yt_ferryman_format', '')
            form.logbroker_tvm_id.data = str(data['delivery_info'].get('logbroker_tvm_id'))
            form.logbroker_traffic_volume.data = data['delivery_info'].get('logbroker_traffic_volume')
            form.service_tvm.data = str(data.get('service_tvm'))
            form.service_saas_tvm.data = str(data.get('service_saas_tvm'))
            form.service_ctype.data = data['service_ctype']
            form.memory_requirements.data = data['req_memory']
            form.cpu_requirements.data = data['req_cpu']
            if 'prestable' not in data['service_ctype']:
                form.search_rps.data = data['sla_info'].get('search_rps')
                form.index_size.data = data['sla_info']['total_index_size_bytes']
                form.maxdocs.data = data['sla_info']['maxdocs']
                form.search_q_99_ms.data = data['sla_info']['search_q_99_ms']
                form.search_q_999_ms.data = data['sla_info']['search_q_999_ms']
    form.comment.data = 'Модификация параметров заявки'
    return form
