# coding: utf-8

from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

from six import iteritems

from saas.library.python.nanny_rest.recipe import AlemateRecipe
from saas.library.python.nanny_rest.tickets_integration.tickets_integration import TicketsIntegration


class NannyServiceBaseInfoProxy(object):
    def __init__(self, initial_state):
        self._info_attrs = initial_state
        self.category = self._info_attrs.pop('category')
        self.abc_group = self._info_attrs.pop('abc_group')
        self.description = self._info_attrs.pop('desc')
        self.tickets_integration = TicketsIntegration(**self._info_attrs.pop('tickets_integration'))
        self.labels = {label['key']: label.get('value', None) for label in self._info_attrs.pop('labels')}

    @property
    def info_attrs_content(self):
        base_dict = self._info_attrs
        base_dict['category'] = self.category
        base_dict['abc_group'] = self.abc_group
        base_dict['desc'] = self.description
        base_dict['labels'] = [{'key': k, 'value': v} for k, v in iteritems(self.labels) if v is not None]
        base_dict['tickets_integration'] = self.tickets_integration.dict()
        return base_dict

    @property
    def recipes(self):
        return {r['id']: AlemateRecipe(**r) for r in self.info_attrs_content['recipes']['content']}

    @recipes.setter
    def recipes(self, value):
        self._info_attrs['recipes']['content'] = [r.dict() for r in value.values()]

    @property
    def prepare_recipes(self):
        return {r['id']: AlemateRecipe(**r) for r in self.info_attrs_content['recipes']['prepare_recipes']}

    @prepare_recipes.setter
    def prepare_recipes(self, value):
        self._info_attrs['recipes']['prepare_recipes'] = [r.dict() for r in value.values()]

    def add_or_update_recipe(self, recipe):
        current_recipes = self.recipes
        current_recipes[recipe.id] = recipe
        self.recipes = current_recipes

    def add_or_update_recipes(self, recipes):
        current_recipes = self.recipes
        for recipe in recipes:
            current_recipes[recipe.id] = recipe
        self.recipes = current_recipes

    def add_or_update_prepare_recipe(self, recipe):
        current_recipes = self.prepare_recipes
        current_recipes[recipe.id] = recipe
        self.prepare_recipes = current_recipes

    def add_or_update_prepare_recipes(self, recipes):
        current_recipes = self.recipes
        for recipe in recipes:
            current_recipes[recipe.id] = recipe
        self.prepare_recipes = current_recipes
