#!/usr/bin/env python3

# ~ Empresa Libre
# ~ Copyright (C) 2016-2018  Mauricio Baeza Servin (publico@cuates.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/>.

import logbook
import os
import sys
from mako.lookup import TemplateLookup
from logbook import Logger, StreamHandler, RotatingFileHandler
logbook.set_datetime_format('local')

from conf import DEBUG, MV, LOG_PATH

try:
    from conf import DEFAULT_PASSWORD
except ImportError:
    DEFAULT_PASSWORD = 'salgueiro4.0'

TITLE_APP = 'Empresa Libre'

try:
    from conf import NO_HTTPS
except ImportError:
    NO_HTTPS = True


DEBUG = DEBUG
VERSION = '2.3.0'

EMAIL_SUPPORT = ('soporte@empresalibre.mx',)
TITLE_APP = '{} v{}'.format(TITLE_APP, VERSION)

BASE_DIR = os.path.abspath(os.path.dirname(__file__))
COMPANIES = os.path.abspath(os.path.join(BASE_DIR, '..', 'db', 'rfc.db'))

path_static = os.path.abspath(os.path.join(BASE_DIR, '..', 'static'))
path_docs = os.path.abspath(os.path.join(BASE_DIR, '..', 'docs'))

path_css = os.path.join(path_static, 'css')
path_img = os.path.join(path_static, 'img')
path_user_template = os.path.join(path_docs, 'templates')
path_user_logos = os.path.join(path_docs, 'logos')

# ~ PATH_STATIC = os.path.abspath(os.path.join(BASE_DIR, '..'))

PATH_TEMPLATES = os.path.abspath(os.path.join(BASE_DIR, '..', 'templates'))
PATH_MEDIA = os.path.abspath(os.path.join(BASE_DIR, '..', 'docs'))

PATH_CP = os.path.abspath(os.path.join(BASE_DIR, '..', 'db', 'cp.db'))
COMPANIES = os.path.abspath(os.path.join(BASE_DIR, '..', 'db', 'rfc.db'))
DB_SAT = os.path.abspath(os.path.join(BASE_DIR, '..', 'db', 'sat.db'))

PATH_SESSIONS = {
    'data': os.path.abspath(os.path.join(BASE_DIR, '..', 'cache', 'data')),
    'lock': os.path.abspath(os.path.join(BASE_DIR, '..', 'cache', 'lock')),
}

IV = 'valores_iniciales.json'
INIT_VALUES = os.path.abspath(os.path.join(BASE_DIR, '..', 'db', IV))
# ~ CT = 'cancel_template.xml'
# ~ TEMPLATE_CANCEL = os.path.abspath(os.path.join(PATH_TEMPLATES, CT))

PATH_XSLT = os.path.abspath(os.path.join(BASE_DIR, '..', 'xslt'))
PATH_BIN = os.path.abspath(os.path.join(BASE_DIR, '..', 'bin'))

PATH_TEMPLATES_USER = os.path.abspath(os.path.join(
    BASE_DIR, '..', 'docs', 'templates'))
directories=[PATH_TEMPLATES, PATH_TEMPLATES_USER]
template_lookup = TemplateLookup(directories=directories,
    input_encoding='utf-8',
    output_encoding='utf-8')

LOG_NAME = 'API'
LOG_LEVEL = 'INFO'

format_string = '[{record.time:%d-%b-%Y %H:%M:%S}] ' \
    '{record.level_name}: ' \
    '{record.channel}: ' \
    '{record.message}'


if DEBUG:
    LOG_LEVEL = 'DEBUG'
    StreamHandler(
        sys.stdout,
        level=LOG_LEVEL,
        format_string=format_string).push_application()
else:
    RotatingFileHandler(
        LOG_PATH,
        backup_count=10,
        max_size=1073741824,
        level=LOG_LEVEL,
        format_string=format_string).push_application()

    StreamHandler(
        sys.stdout,
        level=LOG_LEVEL,
        format_string=format_string).push_application()


log = Logger(LOG_NAME)


PATH_XSLTPROC = 'xsltproc'
PATH_OPENSSL = 'openssl'
PATH_XMLSEC = 'xmlsec1'
if 'win' in sys.platform:
    PATH_XSLTPROC = os.path.join(PATH_BIN, 'xsltproc.exe')
    PATH_OPENSSL = os.path.join(PATH_BIN, 'openssl.exe')
    PATH_XMLSEC = os.path.join(PATH_BIN, 'xmlsec.exe')


PRE_DEFAULT = {
    'CFDI': {'VERSION': '4.0', 'PRE': '{http://www.sat.gob.mx/cfd/4}'},
    'NOMINA': {'VERSION': '1.2', 'PRE': '{http://www.sat.gob.mx/nomina12}'},
    'PAGOS': {'VERSION': '2.0', 'PRE': '{http://www.sat.gob.mx/Pagos20}'},
    'TIBRE': {'VERSION': '1.1', 'PRE': '{http://www.sat.gob.mx/TimbreFiscalDigital}'},
}

pre2 ='{http://www.sat.gob.mx/cfd/2}'
pre3 ='{http://www.sat.gob.mx/cfd/3}'
PRE_HISTORY = {
    'CFDI': {'2.0': pre2, '2.2': pre2,
        '3.0': pre3, '3.2': pre3, '3.3': pre3},
    'NOMINA': {'1.1': '{http://www.sat.gob.mx/nomina}'},
    'PAGOS': {'1.0': '{http://www.sat.gob.mx/Pagos}'},
}

PRE = {
    '2.0': '{http://www.sat.gob.mx/cfd/2}',
    '2.2': '{http://www.sat.gob.mx/cfd/2}',
    '3.0': '{http://www.sat.gob.mx/cfd/3}',
    '3.2': '{http://www.sat.gob.mx/cfd/3}',
    '3.3': '{http://www.sat.gob.mx/cfd/3}',
    '4.0': '{http://www.sat.gob.mx/cfd/4}',
    'TIMBRE': '{http://www.sat.gob.mx/TimbreFiscalDigital}',
    'DONATARIA': '{http://www.sat.gob.mx/donat}',
    'INE': '{http://www.sat.gob.mx/ine}',
    'LOCALES': '{http://www.sat.gob.mx/implocal}',
    'NOMINA': {
        '1.1': '{http://www.sat.gob.mx/nomina}',
        '1.2': '{http://www.sat.gob.mx/nomina12}',
        },
    'PAGOS': {
        '1.0': '{http://www.sat.gob.mx/Pagos}',
    }
}

# To delete
# ~ CURRENT_CFDI = '4.0'
# ~ CURRENT_CFDI_NOMINA = '1.2'

DECIMALES = 2
DECIMALES_TAX = 4
DECIMALES_PRECIOS = 4
IMPUESTOS = {
    'ISR': '001',
    'IVA': '002',
    'IEPS': '003',
    'EXENTO': '000',
    'ISH': '000',
    'INSPECCION DE OBRA': '000',
    'ICIC': '000',
    'CEDULAR': '000',
    'CMIC': '000',
    'SUPERVISION': '000',
}
DEFAULT_SAT_PRODUCTO = '01010101'
DEFAULT_SERIE_TICKET = 'T'
DEFAULT_CFDIPAY = {
    'SERIE': 'FP',
    'TYPE': 'P',
    'WAYPAY': 'PPD',
    'CURRENCY': 'XXX',
    'TC': '1',
    'USED': 'CP01',
    'KEYSAT': '84111506',
    'UNITKEY': 'ACT',
    'DESCRIPTION': 'Pago',
    'TYPE_RELATION': '04',
}
DIR_FACTURAS = 'facturas'
USAR_TOKEN = False
CANCEL_SIGNATURE = False
PUBLIC = 'Público en general'
DEFAULT_SAT_NOMINA = {
    'SERIE': 'N',
    'FORMA_PAGO': '99',
    'USO_CFDI': 'CN01',
    'CLAVE': '84111505',
    'UNIDAD': 'ACT',
    'DESCRIPCION': 'Pago de nómina',
}

API = 'https://api.empresalibre.net{}'

CURRENCY_MN = 'MXN'

# ~ v2
CANCEL_VERSION = ('3.3', '4.0')
CFDI_VERSIONS = CANCEL_VERSION

IS_MV = MV
DB_COMPANIES = os.path.abspath(os.path.join(BASE_DIR, '..', 'db', 'rfc.db'))
path_bk = os.path.join(path_docs, 'tmp')
path_local = 'facturas'
path_sat = os.path.abspath(os.path.join(BASE_DIR, '..', 'db', 'valores_iniciales.json'))

EXT = {
    'CSS': 'css',
    'HTML': 'html',
    'ODS': 'ods',
    'PNG': 'png',
    'JSON': 'json',
}
MXN = 'MXN'

CARTA_PORTE = {
    'MONEDA': 'XXX',
}

PATHS = {
    'STATIC': path_static,
    'CSS': path_css,
    'IMG': path_img,
    'DOCS': path_docs,
    'USER': path_user_template,
    'LOGOS': path_user_logos,
    'BK': path_bk,
    'LOCAL': path_local,
    'SAT': path_sat,
    'xslt': PATH_XSLT,
}

VALUES_PDF = {
    'CANCEL': {True: 'inline', False: 'none'},
    'TYPE': {'I': 'Ingreso', 'E': 'Egreso', 'T': 'Traslado'},
    'TAX': {'001': 'ISR', '002': 'IVA', '003': 'IEPS'},
    'METHOD': {
        'PUE': 'Pago en una sola exhibición',
        'PPD': 'Pago en parcialidades o diferido',
    },
}

RESICO = '626'

RFCS = {
    'PUBLIC': 'XAXX010101000',
    'FOREIGN': 'XEXX010101000',
    'CVD110412TF6': 'finkok',
    'SCD110105654': 'comercio',
    'AAA010101AAA': 'comercio',
    'SPR190613I52': 'comercio',
}

URL = {
    'SEAFILE': 'https://seafile.cuates.net',
}

DEFAULT_GLOBAL = {
    'cantidad': 1.00,
    'unidad': 'ACT',
    'descripcion': 'Venta',
    'clave_sat': '01010101',
}

# ~ TEMPLATE_CANCEL = """<CancelaCFD xmlns="http://cancelacfd.sat.gob.mx">
# ~ <Cancelacion xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" RfcEmisor="{rfc}" Fecha="{fecha}">
  # ~ <Folios>
    # ~ <Folio UUID="{uuid}" Motivo="{motivo}"{folio}/>
  # ~ </Folios>
  # ~ <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
    # ~ <SignedInfo>
      # ~ <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
      # ~ <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
      # ~ <Reference URI="">
        # ~ <Transforms>
          # ~ <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
        # ~ </Transforms>
        # ~ <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
        # ~ <DigestValue/>
      # ~ </Reference>
    # ~ </SignedInfo>
    # ~ <SignatureValue/>
    # ~ <KeyInfo>
      # ~ <X509Data>
        # ~ <X509IssuerSerial>
          # ~ <X509IssuerName/>
          # ~ <X509SerialNumber/>
        # ~ </X509IssuerSerial>
        # ~ <X509Certificate/>
      # ~ </X509Data>
      # ~ <KeyValue>
        # ~ <RSAKeyValue>
          # ~ <Modulus/>
          # ~ <Exponent/>
        # ~ </RSAKeyValue>
      # ~ </KeyValue>
    # ~ </KeyInfo>
  # ~ </Signature>
# ~ </Cancelacion>
# ~ </CancelaCFD>"""

TEMPLATE_CANCEL = """<CancelaCFD xmlns="http://cancelacfd.sat.gob.mx"><Cancelacion xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Fecha="{fecha}" RfcEmisor="{rfc}" xmlns="http://cancelacfd.sat.gob.mx"><Folios><Folio UUID="{uuid}" Motivo="{motivo}"{folio}/></Folios><Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /><Reference URI=""><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /><DigestValue/></Reference></SignedInfo><SignatureValue/><KeyInfo><X509Data><X509IssuerSerial><X509IssuerName/><X509SerialNumber/></X509IssuerSerial><X509Certificate/></X509Data><KeyValue><RSAKeyValue><Modulus/><Exponent/></RSAKeyValue></KeyValue></KeyInfo></Signature></Cancelacion></CancelaCFD>"""
