
from configs.firebase import db
from zeep import Client, Settings

CREDS = dict(
    SANMAR=dict(
        username = "Awearllc",
        password = "Awear123!",
        name = "SanMar",
        id = "SANMAR"
    ),
    SS = dict(
        username = "526375",
        password = "71b11f7f-c6d0-42d9-928e-07f2d9764bcb",
        name = "S&S Activewear",
        id = "SS"
    ),
    AB= dict(
        username = "32361972",
        password = "Awear123!",
        name = "Alphabroder",
        id="AB"
    )
)

def getClient(supplierId, endpoint='products'):
    ref = db.collection('suppliers').document(supplierId).collection("wdsl").document(endpoint).get()
    if ref.exists:
        data = ref.to_dict()
        settings = Settings(strict=False, xml_huge_tree=True)
        client = Client(data.get('url'), settings=settings)
        return client, str(data.get('version'))
    return None

def getSupplierById(id:str, credentials = False):
    ref = db.collection("suppliersCredentials" if credentials else "suppliers").document(id).get()
    if ref.exists:
        return ref.to_dict()
    return None

def getSuppliers(credentials = False, private = False):
    ref = db.collection("suppliersCredentials" if credentials else "suppliers").where('private', '==', private).get()
    return [r.to_dict() for r in ref]

def getSupplierCredentials(id, enterpriseId=None):
    ref = db.collection('suppliersCredentials').document(id+(enterpriseId if enterpriseId else "BSSLIiNy1oIgVazwv0iO")).get()
    if ref.exists:
        return ref.to_dict()
    else:
        return CREDS.get(id)

def saveSupplier(**data):
    supplier = getSupplierById(id)
    if supplier:
        supplier.update(data)
        ref = db.collection('suppliersCredentials').document(id)
        ref.set(supplier, merge=True)
        return id
    return None