from trytond.pool import Pool
from trytond.transaction import Transaction
import datetime


ITSA_COMPANY_NAME = 'ITSA'


def record_id(record):
    return getattr(record, 'id', record)


def is_itsa_company(company=None):
    if company is None:
        company_id = Transaction().context.get('company')
        if not company_id:
            return False
        Company = Pool().get('company.company')
        company = Company(company_id)
    party = getattr(company, 'party', None)
    return bool(party and party.name == ITSA_COMPANY_NAME)


def _search_first(model_name, domains):
    Model = Pool().get(model_name)
    for domain in domains:
        try:
            records = Model.search(domain, limit=1)
        except Exception:
            continue
        if records:
            return records[0]


def default_itsa_currency():
    currency = _search_first('currency.currency', [
            [('code', '=', 'USD')],
            [('name', '=', 'USD')],
            [('symbol', '=', 'USD')],
            ])
    return record_id(currency) if currency else None


def default_itsa_price_fix_type():
    fix_type = _search_first('price.fixtype', [
            [('name', '=', 'Market Price')],
            [('name', '=', 'Market price')],
            [('name', 'ilike', 'Market Price')],
            ])
    return record_id(fix_type) if fix_type else None


def default_itsa_price_calendar():
    calendar = _search_first('price.calendar', [
            [('name', '=', 'Argus Sulphuric Acid')],
            [('name', 'ilike', 'Argus Sulphuric Acid')],
            ])
    return record_id(calendar) if calendar else None


def default_itsa_unit():
    unit = _search_first('product.uom', [
            [('symbol', '=', 'Mt')],
            [('name', '=', 'Mt')],
            [('symbol', '=', 'MT')],
            [('name', '=', 'MT')],
            ])
    return record_id(unit) if unit else None


def default_itsa_bulk_unit():
    unit = _search_first('product.uom', [
            [('symbol', '=', 'Bulk')],
            [('name', '=', 'Bulk')],
            [('symbol', '=', 'bulk')],
            [('name', '=', 'bulk')],
            ])
    return record_id(unit) if unit else None


def _company_from_values(values):
    company = values.get('company')
    if company and hasattr(company, 'party'):
        return company
    company_id = record_id(company) or Transaction().context.get('company')
    if not company_id:
        return None
    return Pool().get('company.company')(company_id)


def _dimension(name):
    return _search_first('analytic.dimension', [
            [('code', '=', name)],
            [('name', '=', name)],
            [('code', 'ilike', '%%%s%%' % name)],
            [('name', 'ilike', '%%%s%%' % name)],
            ])


def _book_year_suffix(today=None):
    if today is None:
        today = Pool().get('ir.date').today()
    year = today.year
    if today < datetime.date(year, 4, 1):
        year -= 1
    return '%02d' % (year % 100)


def _book_value(dimension, today=None):
    if not dimension:
        return None
    suffix = _book_year_suffix(today)
    return _search_first('analytic.dimension.value', [
            [
                ('dimension', '=', record_id(dimension)),
                ('code', 'ilike', '%%%s%%' % suffix),
                ],
            [
                ('dimension', '=', record_id(dimension)),
                ('name', 'ilike', '%%%s%%' % suffix),
                ],
            ])


def default_itsa_analytic_dimension_assignments(company=None, today=None):
    if not is_itsa_company(company):
        return []

    assignments = []
    book = _dimension('Book')
    if book:
        value = _book_value(book, today=today)
        assignments.append({
                'dimension': record_id(book),
                'value': record_id(value) if value else None,
                })

    strategy = _dimension('Strategy')
    if strategy:
        assignments.append({
                'dimension': record_id(strategy),
                'value': None,
                })

    return assignments


def add_itsa_analytic_dimension_defaults(values):
    if values.get('analytic_dimensions'):
        return
    company = _company_from_values(values)
    assignments = default_itsa_analytic_dimension_assignments(company=company)
    if assignments:
        values['analytic_dimensions'] = [('create', assignments)]
