from .Shop import Shop
from .Product import Product
from bs4 import BeautifulSoup
import requests

class ShopAlternateDE(Shop):

    dom_class_1 = "grid-container"
    dom_class_2 = "card"

    def getDomain(self):
        return 'alternate.de'

    def handlePyResponse(self, resp):
        return self.fillProductsFromResp(resp)
        
    def handleSeleniumResponse(self, webdriver):
        resp = self.seleniumGetSourceByWaitForClass(self.dom_class_1)
        if resp:
            return self.fillProductsFromResp(resp)
        else:
            return None

    def fillProductsFromResp(self, resp):
        soup = BeautifulSoup(resp, features="html.parser")
        if soup.findAll(attrs={'class': self.dom_class_1}).__len__() == 0:
            print("Expected HTML element or class \"%s\" not found!" % self.dom_class_1)
            return False
        try:
            for a in soup.findAll("a", attrs={'class': self.dom_class_2}):
                vendor = a.find(class_='product-name').findAll('span')[0].text.strip()
                name = a.find(class_='product-name').get_text().strip().split(',')[0]
                vendor = 'ZOTAC GAMING' if 'ZOTAC' in vendor.upper() else vendor
                chip = self.getChipName(name)
                price = float(a.find(class_='price').get_text()
                            .replace('-', '00').strip('€').strip('*').strip()
                            .replace('.', '').replace(',', '.'))
                location = self.getDomain()
                buy = a.attrs['href']
                tmp_avlb = a.find(class_='delivery-info').get_text()
                if "Auf Lager" in tmp_avlb:
                    available = 'YES'
                elif "Liefertermin" in tmp_avlb:
                    available = 'NO'
                elif "neu eingetroffen" in tmp_avlb:
                    available = 'SOON'
                else:
                    available = 'UNKNOWN'
                product = Product(vendor.upper(), name, chip, price, location, buy, available)
                self.products.append(product)
            return True
        except Exception as e:
            print("ⓧ Failed. %s" % e)
        return False
