import logging
from typing import Optional, Dict, Any

from company.models.company import Company
from company.serializers.company import CompanySerializer

_log = logging.getLogger(__name__)


class CompanyCreateAndUpdateService:
    """Service for creating, and updating company"""

    def __init__(self, company: Optional[Company], data: Dict[str, Any]):
        _log.debug('Start create or update company')
        self.company = company
        self.data = self.prepare_date(data.copy())

    def prepare_date(self, data: Dict[str, Any]) -> Dict[str, Any]:
        """Prepare data for creating and updating company"""
        location_id = data.get('location')
        if location_id:
            data['location_id'] = location_id
            del data['location']
        return data

    def _update(self) -> Company:
        """Update company data"""
        _log.debug(f'Update company: {self.company}')
        company = self.company
        for attr, value in self.data.items():
            setattr(company, attr, value)
        company.save()
        return company

    def _create(self) -> Company:
        """Create company."""
        company = Company.objects.create(**self.data)
        _log.debug(f'Create company: {company}')
        return company

    def save(self) -> Dict:
        """SAve company data"""
        _log.debug(f'Save company nata: {self.company}')
        if self.company is None:
            company = self._create()
        else:
            company = self._update()
        return CompanySerializer(company).data
