from saas.tools.devops.lib23.saas_entity import SaaSEntity, STABLE_SAAS_CTYPES
from saas.tools.devops.lib23.nanny_helpers import NannyService
from saas.tools.devops.lib2.sandbox_rest_helpers import SandboxTask, Client

import search.tools.devops.libs.utils as u
u.logger_setup(2)

sb_task_name = 'BUILD_RTYSERVER_CONFIG'
sb_task_id = '444343578'
old_sb_task_id = '362046675'


def patch_logrotate(ra):

    task = SandboxTask(Client(), sb_task_id)

    for r in ra["resources"]['sandbox_files']:
        if r['task_type'] == sb_task_name:
            r['task_id'] = sb_task_id
            for sr in task.resources:
                if sr.type == r['resource_type']:
                    r['resource_id'] = str(sr.id)

    for i in range(len(ra['instance_spec']['auxDaemons'])):
        if ra['instance_spec']['auxDaemons'][i]['type'] == 'LOGROTATE':
            del ra['instance_spec']['auxDaemons'][i]

    return ra


def unpatch_logrotate(ra):

    task = SandboxTask(Client(), old_sb_task_id)

    for r in ra["resources"]['sandbox_files']:
        if r['task_type'] == sb_task_name:
            r['task_id'] = old_sb_task_id
            for sr in task.resources:
                if sr.type == r['resource_type']:
                    r['resource_id'] = str(sr.id)

    have_logrotate_flag = False
    for i in range(len(ra['instance_spec']['auxDaemons'])):
        if ra['instance_spec']['auxDaemons'][i]['type'] == 'LOGROTATE':
            have_logrotate_flag = True

    if not have_logrotate_flag:
        ra['instance_spec']['auxDaemons'].append({"type": "LOGROTATE"})

    print ra
    return ra


e = SaaSEntity()
all_stable_services = e.filter_iterate(STABLE_SAAS_CTYPES)
# all_staging_services = e.filter_iterate(STABLE_SAAS_CTYPES)

sample = [{
    'nanny_service': u'saas_cloud_crm',
    'saas_ctype': 'stable',
    'saas_service': u'crm'
}]

all_stable_services = sample

nanny_services = [NannyService(s['nanny_service']) for s in all_stable_services]
unpatched_nanny_services = []

for s in nanny_services:
    try:
        s.patch_runtime_attributes(unpatch_logrotate)
    except:
        unpatched_nanny_services.append(s.name)

print "Unpatched services : {}".format(unpatched_nanny_services)
