# -*- coding: utf-8 -*-
import logging
import backend.yt_cypress
import saas.tools.ssm.modules.startrek_api as startrek_api
import saas.tools.ssm.modules.abc_api as abc_api

yt_client = backend.yt_cypress.SaaSYtJobControl()
startrek_client = startrek_api.SaaSStartrekWorkflow()
abc_client = abc_api.ABCApi()


def get_startrek_issue_num(request_id):
    job_attrs = yt_client.get_job_info(request_id)
    return job_attrs['sla_info']['ticket']


def confirm_request(user, request_id):
    logging.info('Confirm request %s by user %s', request_id, user)
    startrek_ticket = get_startrek_issue_num(request_id)
    if not yt_client.get_approve_status(request_id):
        yt_client.set_approve_status(request_id, True)
        startrek_client.add_comment(startrek_ticket, 'Заявка была подтверждена кем:{}'.format(user))


def unconfirm_request(user, request_id):
    logging.info('Uncomfirm request %s by user %s', request_id, user)
    startrek_ticket = get_startrek_issue_num(request_id)
    if yt_client.get_approve_status(request_id):
        yt_client.set_approve_status(request_id, False)
        startrek_client.add_comment(startrek_ticket, 'Подтверждение заявки было снято кем:{}'.format(user))


def discard_request(user, request_id):
    logging.info('Discarding request %s by user %s', request_id, user)
    startrek_ticket = get_startrek_issue_num(request_id)
    yt_client._remove_lock(request_id)
    yt_client.discard_request(request_id)
    startrek_client.add_comment(startrek_ticket, 'Заявка была отменена кем:{}'.format(user))
    startrek_client.close_issue(startrek_ticket)


def stop_request(user, request_id):
    logging.info('Stopped request %s', request_id)
    startrek_ticket = get_startrek_issue_num(request_id)
    yt_client._remove_lock(request_id)
    yt_client.change_job_status(request_id, 'job', 'STOP')
    startrek_client.add_comment(startrek_ticket, 'Выполнение заявки было приостановлено кем:{}'.format(user))


def start_request(user, request_id):
    logging.info('Started request %s', request_id)
    startrek_ticket = get_startrek_issue_num(request_id)
    yt_client.change_job_status(request_id, 'job', 'IN_PROCESS')
    startrek_client.add_comment(startrek_ticket, 'Выполнение заявки было возобновлено кем:{}'.format(user))
