#!/usr/bin/env python

# ~ Empresa Libre
# ~ Copyright (C) 2016-2018  Mauricio Baeza Servin (web@correolibre.net)
# ~
# ~ This program is free software: you can redistribute it and/or modify
# ~ it under the terms of the GNU General Public License as published by
# ~ the Free Software Foundation, either version 3 of the License, or
# ~ (at your option) any later version.
# ~
# ~ This program is distributed in the hope that it will be useful,
# ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
# ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# ~ GNU General Public License for more details.
# ~
# ~ You should have received a copy of the GNU General Public License
# ~ along with this program.  If not, see <http://www.gnu.org/licenses/>.

from . import main


class StorageEngine(object):

    def __init__(self):
        pass

    def authenticate(self, args):
        return main.authenticate(args)

    def get_employees(self, values):
        return main.Empleados.get_by(values)

    def get_nomina(self, values):
        return main.CfdiNomina.get_by(values)

    def empresa_agregar(self, values):
        # ~ return main.empresa_agregar(values['alta_rfc'], False)
        return main._new_client(values['alta_rfc'], False)

    def empresa_borrar(self, values):
        # ~ return main.empresa_borrar(values['rfc'])
        return main._delete_client(values['rfc'], False, False)

    def respaldar_dbs(self):
        return main.respaldar_dbs()

    def get_values(self, table, values=None, session=None):
        if table in ('allusuarios', 'usuarioupdate', 'main'):
            return getattr(self, '_get_{}'.format(table))(values, session)
        return getattr(self, '_get_{}'.format(table))(values)

    def _get_timbres(self, values):
        return main.Emisor.get_timbres()

    def _get_schoolgroups(self, values):
        return main.Grupos.get_by(values)

    def _get_nivedusat(self, values):
        return main.SATNivelesEducativos.get_by()

    def _get_niveduall(self, values):
        return main.NivelesEducativos.get_all()

    def _get_titlelogin(self, values):
        return main.get_title_app(2)

    def _get_canopenpre(self, values):
        return main.PreFacturasDetalle.can_open(values['id'])

    def _get_importinvoice(self, values):
        return main.import_invoice()

    def _get_importceods(self, values):
        return main.import_ceods()

    def _get_main(self, values, session):
        return main.config_main(session['userobj'])

    def _get_configtimbrar(self, values):
        return main.config_timbrar()

    def _get_invoicenotes(self, values):
        return main.Facturas.get_notes(values['id'])

    def save_invoice_notes(self, values):
        return main.Facturas.save_notes(values)

    def _get_configticket(self, values):
        return main.config_ticket()

    def _get_saldocuenta(self, values):
        return main.CuentasBanco.get_saldo(values['id'])

    def _get_validartimbrar(self, values):
        return main.validar_timbrar()

    def _get_preproductos(self, values):
        return main.PreFacturasDetalle.facturar(values['id'])

    def upload_file(self, session, table, file_obj):
        if not 'rfc' in session:
            return {'status': 'error'}
        return main.upload_file(session['rfc'], table, file_obj)

    def get_config(self, values):
        return main.Configuracion.get_(values)

    def add_config(self, values):
        return main.Configuracion.add(values)

    def add_cert(self, file_obj):
        return main.Certificado.add(file_obj)

    def validate_cert(self, values, session):
        return main.Certificado.validate(values, session)

    def validate_email(self, values):
        return main.test_correo(values)

    def send_email(self, values, session):
        return main.Facturas.send(values['id'], session['rfc'])

    def enviar_prefac(self, values):
        return main.PreFacturas.enviar(values['id'])

    def _get_verifysat(self, values):
        return main.Facturas.get_verify_sat(values['id'])

    def _get_filteryears(self, values):
        years1 = main.Facturas.filter_years()
        years2 = main.PreFacturas.filter_years()
        return [years1, years2]

    def _get_filteryearsticket(self, values):
        return main.Tickets.filter_years()

    def _get_filteryearsnomina(self, values):
        return main.CfdiNomina.filter_years()

    def _get_cuentayears(self, values):
        return main.CuentasBanco.get_years()

    def _get_cert(self, values):
        return main.Certificado.get_data()

    def _get_cp(self, values):
        return main.get_cp(values['cp'])

    def _get_formapago(self, values):
        return main.SATFormaPago.get_activos(values)

    def _get_tiporelacion(self, values):
        return main.SATTipoRelacion.get_activos(values)

    def _get_condicionespago(self, values):
        return main.CondicionesPago.get_()

    def _get_categorias(self, values):
        return main.Categorias.get_all()

    def _get_newkey(self, values):
        return main.Productos.next_key()

    def _get_unidades(self, values):
        return main.SATUnidades.get_activos()

    def _get_unitbykey(self, values):
        return main.SATUnidades.get_activos_by_key()

    def add_moneda(self, values):
        return main.SATMonedas.add(values)

    def add_unidad(self, values):
        return main.SATUnidades.add(values)

    def add_impuesto(self, values):
        return main.SATImpuestos.add(values)

    def add_usuario(self, values):
        return main.Usuarios.add(values)

    def edit_usuario(self, values):
        return main.Usuarios.edit(values)

    def _get_taxes(self, values):
        return main.SATImpuestos.get_activos()

    def _get_alltaxes(self, values):
        return main.SATImpuestos.get_()

    def _get_allcurrencies(self, values):
        return main.SATMonedas.get_()

    def _get_allbancos(self, values):
        return main.SATBancos.get_()

    def _get_allunidades(self, values):
        return main.SATUnidades.get_()

    def _get_allformasdepago(self, values):
        return main.SATFormaPago.get_()

    def _get_allusoscfdi(self, values):
        return main.SATUsoCfdi.get_all()

    def _get_allregimenes(self, values):
        filters = {'opt': 'all'}
        return main.SATRegimenes.get_data(filters, None)

    def _get_allusuarios(self, values, session):
        return main.Usuarios.get_(session['userobj'])

    def _get_usuarioupdate(self, values, session):
        return main.Usuarios.actualizar(values, session['userobj'])

    def _get_taxupdate(self, values):
        return main.SATImpuestos.actualizar(values)

    def _get_currencyupdate(self, values):
        return main.SATMonedas.actualizar(values)

    def _get_bancoupdate(self, values):
        return main.SATBancos.actualizar(values)

    def _get_emisorbancoupdate(self, values):
        return main.CuentasBanco.activate(values)

    def _get_unidadupdate(self, values):
        return main.SATUnidades.actualizar(values)

    def _get_formasdepagoupdate(self, values):
        return main.SATFormaPago.actualizar(values)

    def _get_usocfdiupdate(self, values):
        return main.SATUsoCfdi.actualizar(values)

    def _get_regimenesupdate(self, values):
        return main.SATRegimenes.actualizar(values)

    def _get_emisorcuentasbanco(self, values):
        return main.CuentasBanco.emisor()

    def _get_satkey(self, values):
        return main.get_sat_key(values['key'])

    def _get_satmonedas(self, values):
        return main.get_sat_monedas(values['key'])

    def _get_satunidades(self, values):
        return main.get_sat_unidades(values['key'])

    def _get_satunidadespeso(self, values):
        return main.get_sat_unidadespeso(values['key'])

    def _get_satproductos(self, values):
        return main.get_sat_productos(values['key'])

    def _get_series(self, values):
        return main.Folios.get_all()

    def _get_monedas(self, values):
        return main.SATMonedas.get_activos()

    def _get_monedasid(self, values):
        return main.SATMonedas.get_activos_by_id()

    def _get_bancosid(self, values):
        return main.SATBancos.get_activos_by_id()

    def _get_regimenes(self, values):
        return main.Emisor.get_regimenes()

    def _get_usocfdi(self, values):
        return main.SATUsoCfdi.get_activos()

    def _get_ebancomov(self, values):
        return main.MovimientosBanco.con(values['id'])

    def delete(self, table, id, user=None):
        if table == 'partner':
            return main.Socios.remove(id)
        if table == 'product':
            return main.Productos.remove(id)
        if table == 'invoice':
            return main.Facturas.remove(id, user)
        if table == 'folios':
            return main.Folios.remove(id)
        if table == 'preinvoice':
            return main.PreFacturas.remove(id)
        if table == 'satimpuesto':
            return main.SATImpuestos.remove(id)
        if table == 'satunit':
            return main.SATUnidades.remove(id)
        if table == 'cuentasbanco':
            return main.CuentasBanco.remove(id)
        if table == 'movbanco':
            return main.MovimientosBanco.remove(id)
        if table == 'usuario':
            return main.Usuarios.remove(id)
        if table == 'config':
            return main.Configuracion.remove(id)
        if table == 'nivedu':
            return main.NivelesEducativos.remove(id)
        if table == 'students':
            return main.Alumnos.remove(id)
        if table == 'employee':
            return main.Empleados.remove(id)
        if table == 'nomina':
            return main.CfdiNomina.remove(id)
        return False

    def _get_client(self, values):
        return main.Socios.get_by_client(values)

    def _get_student(self, values):
        return main.Alumnos.get_by_name(values)

    def _get_product(self, values):
        return main.Productos.get_by(values)

    def _get_productokey(self, values):
        return main.Productos.get_by_key(values)

    def get_partners(self, values):
        return main.Socios.get_(values)

    def partner(self, values):
        if 'opt' in values:
            return main.Socios.opt(values)

        id = int(values.pop('id', '0'))
        if id:
            return main.Socios.actualizar(values, id)

        return main.Socios.add(values)

    def get_products(self, values):
        return main.Productos.get_(values)

    def products(self, values):
        id = int(values.pop('id', '0'))
        if id:
            return main.Productos.actualizar(values, id)

        opt = values.get('opt', '')
        if opt:
            return main.Productos.opt(values)

        return main.Productos.add(values)

    def invoice(self, values, user):
        if 'opt' in values:
            return main.Facturas.opt(values, user)

        id = int(values.pop('id', '0'))
        if id:
            return main.Facturas.actualizar(values, id)

        return main.Facturas.add(values, user)

    def invoice_put(self, values, user):
        return main.Facturas.put(values, user)

    def preinvoice(self, values):
        id = int(values.pop('id', '0'))
        #~ if id:
            #~ return main.PreFacturas.actualizar(values, id)
        return main.PreFacturas.add(values)

    def get_students(self, values):
        return main.Alumnos.get_by(values)

    def students(self, values):
        opt = values.pop('opt')
        if opt == 'add':
            return main.Alumnos.add(values['values'])
        if opt == 'edit':
            return main.Alumnos.actualizar(values['values'])

    def tickets(self, values, user):
        opt = values.pop('opt')
        if opt == 'add':
            return main.Tickets.add(values, user)
        if opt == 'cancel':
            return main.Tickets.cancel(values, user)
        if opt == 'invoice':
            return main.Tickets.invoice(values, user)
        if opt == 'print':
            return main.Tickets.printer(values)

    def get_tickets(self, values, user):
        return main.Tickets.get_by(values, user)

    def get_invoices(self, filters, user):
        if filters.get('by', ''):
            return main.Facturas.get_by(filters, user)
        return main.Facturas.get_(filters)

    def get_preinvoices(self, values):
        return main.PreFacturas.get_(values)

    # ~ def _get_timbrar(self, values):
        # ~ return main.Facturas.timbrar(values)

    def _get_anticipoegreso(self, values):
        return main.Facturas.anticipo_egreso(int(values['id']))

    def get_emisor(self, rfc):
        return main.Emisor.get_(rfc)

    def emisor(self, values):
        return main.Emisor.add(values)

    def cuentasbanco(self, values):
        return main.CuentasBanco.add(values)

    # ~ def add_movbanco(self, values):
        # ~ return main.MovimientosBanco.add(values)

    def get_cuentasbanco(self, values):
        return main.CuentasBanco.get_(values)

    def get_folios(self):
        return main.Folios.get_()

    def add_folios(self, values):
        return main.Folios.add(values)

    def add_nivel_educativo(self, values):
        return main.NivelesEducativos.add(values)

    def get_doc(self, type_doc, id, rfc):
        return main.get_doc(type_doc, id, rfc)

    def get_movimientosbanco(self, values):
        return main.MovimientosBanco.get_(values)

    def importar_bdfl(self):
        return main.importar_bdfl()

    # ~ Revisado
    def get_invoicepay(self, values):
        return main.FacturasPagos.get_values(values)

    def get_cfdipay(self, values):
        return main.CfdiPagos.get_values(values)

    def get_sat_bancos(self, values):
        return main.SATBancos.get_values(values)

    def get_sat_forma_pago(self, values):
        return main.SATFormaPago.get_values(values)

    def get_partners_accounts_bank(self, values):
        return main.SociosCuentasBanco.get_values(values)

    def cfdipay(self, values):
        return main.CfdiPagos.post(values)

    def bankmovement(self, values):
        return main.MovimientosBanco.post(values)

    def sat_bancos(self, values):
        return main.SATBancos.post(values)

    def sat_forma_pago(self, values):
        return main.SATFormaPago.post(values)

    def partners_accounts_bank(self, values):
        return main.SociosCuentasBanco.post(values)

    def nomina(self, values, user):
        return main.CfdiNomina.post(values, user)

    def sat_leyendas_fiscales_get(self, values):
        return main.SATLeyendasFiscales.get_values(values)

    def sat_leyendas_fiscales_post(self, values):
        return main.SATLeyendasFiscales.post(values)

    def sat_leyendas_fiscales_delete(self, values):
        return main.SATLeyendasFiscales.remove(values)

    # ~ v2
    def cert_get(self, filters):
        return main.Certificado.get_data(filters)

    def cert_post(self, filters):
        return main.Certificado.post(filters)

    def sucursales_get(self, filters):
        return main.Sucursales.get_data(filters)

    def sucursales_post(self, filters):
        return main.Sucursales.post(filters)

    def partner_products_get(self, filters):
        return main.PartnerProducts.get_data(filters)

    def inventory_entries_get(self, filters):
        return main.InventoryEntries.get_data(filters)

    def inventory_entries_post(self, filters, user):
        return main.InventoryEntries.post(filters, user)

    def warehouse_get(self, filters):
        return main.Almacenes.get_data(filters)

    def warehouse_post(self, values, user):
        return main.Almacenes.post(values, user)

    def warehouseproduct_get(self, filters, user):
        return main.WareHouseProduct.get_data(filters, user)

    def warehouseproduct_post(self, filters, user):
        return main.WareHouseProduct.post(filters, user)

    def users_get(self, filters, user):
        return main.Usuarios.get_data(filters, user)

    def users_post(self, args, user):
        return main.Usuarios.post(args, user)

    def ticketsdetails_get(self, filters, user):
        return main.TicketsDetalle.get_data(filters, user)

    def products_get(self, filters, user):
        return main.Productos.get_data(filters, user)

    def nomina_get(self, filters, user):
        return main.CfdiNomina.get_data(filters, user)

    def sat_unidades_peso_get(self, filters, user):
        return main.SATUnidadesPeso.get_data(filters, user)

    def sat_unidades_peso_post(self, args, user):
        return main.SATUnidadesPeso.post(args, user)

    def sat_regimenes_get(self, filters, user):
        return main.SATRegimenes.get_data(filters, user)

    def socios_regimenes_get(self, filters, user):
        return main.SociosRegimenes.get_data(filters, user)

    # Companies only in MV
    def _get_empresas(self, values):
        return main.companies_get()

