# This file is part of Tryton.  The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
from __future__ import with_statement

from trytond.model import Workflow, ModelView, ModelSQL, fields
from trytond.pyson import Eval, If, In, Get
from trytond.transaction import Transaction
from trytond.pool import Pool
from .exceptions import CrmConfigurationError
from trytond.i18n import gettext

STATES = {
    'readonly': (Eval('state') != 'draft'),
}


class Activity(Workflow, ModelSQL, ModelView):
    'Activity'
    __name__ = 'crm.activity'
    _rec_name = 'number'
    number = fields.Char('Number', readonly=True)
    contact = fields.Char('Contact', states=STATES, required=True, select=True)
    customer = fields.Many2One('party.party', 'Customer', states=STATES, select=True)
    subject = fields.Char('Subject', states=STATES, select=True)
    media = fields.Selection([
            ('phone', 'Phone'),
            ('mobile', 'Mobile'),
            ('videochat', 'Videochat'),
            ('email', 'Email'),
            ], 'Media', states=STATES, depends=['state'], required=True)
    media_info = fields.Char('Media Info', states=STATES)
    planned_date = fields.Date('Planned Date', states=STATES, required=True)
    effective_date = fields.Date('Effective Date', states=STATES)
    notes = fields.Text('Notes', states=STATES)
    company = fields.Many2One('company.company', 'Company', required=True,
            states=STATES, domain=[ ('id', If(In('company',
            Eval('context', {})), '=', '!='), Get(Eval('context', {}),
            'company', 0)), ])
    state = fields.Selection([
            ('draft', 'Draft'),
            ('pending', 'Pending'),
            ('done', 'Done'),
            ('cancelled', 'Cancelled'),
        ], 'State', readonly=True, required=True)
    state_string = state.translated('state')

    @classmethod
    def __setup__(cls):
        super(Activity, cls).__setup__()
        cls._order.insert(0, ('planned_date', 'DESC'))
        cls._order.insert(1, ('id', 'DESC'))
        cls._transitions |= set((
                ('draft', 'pending'),
                ('pending', 'done'),
                ('pending', 'draft'),
                ('pending', 'cancelled'),
                ('cancelled', 'draft'),
            ))
        cls._buttons.update({
                'draft': {
                    'invisible': Eval('state').in_(['draft', 'done']),
                    },
                'cancel': {
                    'invisible': Eval('state').in_(['cancelled', 'done']),
                    },
                'pending': {
                    'invisible': Eval('state') != 'draft',
                    },
                'done': {
                    'invisible': Eval('state') != 'pending',
                    },
                })

    @staticmethod
    def default_company():
        return Transaction().context.get('company') or False

    @staticmethod
    def default_state():
        return 'draft'

    @classmethod
    @ModelView.button
    @Workflow.transition('done')
    def done(cls, records):
        pass

    @classmethod
    @ModelView.button
    @Workflow.transition('pending')
    def pending(cls, records):
        for record in records:
            record.set_number()

    @classmethod
    @ModelView.button
    @Workflow.transition('cancelled')
    def cancel(cls, records):
        pass

    @classmethod
    @ModelView.button
    @Workflow.transition('draft')
    def draft(cls, records):
        pass

    def set_number(self):
        '''
        Set sequence number
        '''
        if self.number:
            return
        pool = Pool()
        Config = pool.get('crm.configuration')
        config = Config.get_configuration()
        if not config.activity_sequence:
            raise CrmConfigurationError(
                gettext('crm.msg_missing_sequence_activity'))

        seq = config.activity_sequence.get()
        self.write([self], {'number': seq})
