from app.commons.forms import ComboBox


class StoreView(object):
    """
    Class for that all changes in store data update view fields and database
    """

    def __init__(self, parent, fields):
        self.parent = parent
        self.Sale = parent.Sale
        self.store = {f: None for f in fields}

    def set_sale(self, sale_id):
        self.sale_id = sale_id

    def get(self, field_name):
        field = self.store[field_name]
        return field

    def clear(self):
        self.sale_id = None
        for k, v in self.store.items():
            field = getattr(self.parent, 'field_' + k, None)
            if field and hasattr(field, 'setText'):
                field.setText('')

            field_ask = getattr(self.parent, 'field_' + k + '_ask', None)
            if field_ask == 'invoice_number_ask':
                continue
            if field_ask and hasattr(field_ask, 'setText'):
                field_ask.setText('')

            self.store[k] = None

    def set(self, values):
        if values.get('id'):
            self.sale_id = values['id']
        for k, v in values.items():
            self.store[k] = v
            field = getattr(self.parent, 'field_' + k, None)
            if field and hasattr(field, 'setText'):
                if isinstance(v, dict):
                    val = v.get('rec_name') or v.get('name')
                elif v is None:
                    val = ''
                else:
                    val = v
                field.setText(str(val))
            elif isinstance(field, ComboBox):
                field.set_from_id(v)

    def update(self, values):
        """
        This method update record in database and current view
        values: Dict
        """
        for k, v in values.items():
            self.store[k] = v
            field_name = 'field_' + k

            field = getattr(self.parent, field_name, None)
            if not field:
                continue
            if hasattr(field, 'setText'):
                if isinstance(v, dict):
                    val = v.get('rec_name') or v.get('name') or v['id']
                else:
                    val = v
                field.setText(str(val))
        print(self.sale_id, values)
        res = self.Sale.write([self.sale_id], values)
        return res
