# -*- coding: utf-8 -*-
"""
Created on June 9 , 2022

@author: lix0
"""
from .base import Api
from common.models import Component
from api.views.jobmetainfo import create_default_kpis
import logging


class RegressGetComponent(Api):

    @staticmethod
    def get(request):
        try:
            name = request.GET['name']
            tag = request.GET['project']
        except KeyError:
            return [{'success': 0, 'error': 'Not enough parameters. Name or project not found'}]
        services = request.GET.get('services', '[]')
        dsc = request.GET.get('dsc', '')
        logging.info('Search or create component: name - %s, project - %s, service - %s', name, tag, services)

        try:
            component_obj = Component.objects.get_or_create(name=name, tag=tag, defaults={'services_json': services, 'dsc': dsc})[0]
            create_default_kpis(component_obj)

        except Exception as exc:
            logging.exception('Component %s was not found and cannot be created')
            return [{'success': 0, 'error': exc.__class__.__name__}]
        
        return [{'success': 1, 'component': component_obj.n}]
