#!/usr/bin/python3
# coding: utf-8

#################################################################
#
# Copyright (C) ИП Пуляев Григорий Васильевич, 2024
# email: rodegast@xmail.ru
# telegram: t.me/kybyc_meta_test
#
# Расширение добавляет поддержку браузера Chromium
# в платформу автоматизированного тестирования Meta Test.
#
# Этот файл НЕ является частью платформы Meta Test.
# Лицензия расширения - Apache License 2.0
# https://www.apache.org/licenses/LICENSE-2.0
#
#################################################################

from functools import lru_cache

from selenium.webdriver.chromium.options import ChromiumOptions
from selenium.webdriver.chromium.service import ChromiumService
from selenium.webdriver.chromium.webdriver import ChromiumDriver

from core_brower import WebBrowser
from .chrome import get_chromedriver
from utilites import Version, get_exec_prog, get_platform
from parameter import CONFIG, LOG_TYPES, LOG_LEVEL, ItemConfig

class Chromium(WebBrowser):
	@lru_cache
	def installed_versions(self):
		platform = get_platform()
		if platform == "mac-x64":
			return self.mac_installed_version(r"/Applications/Chromium.app/Contents/MacOS/Chromium")
		elif platform == "linux64":
			return self.linux_installed_version(["chromium", "chromium-browser", "chromium-gost"])
		return self.windows_installed_version((
			r"PROGRAMFILES\\Chromium\\Application\\chrome.exe"
			, r"PROGRAMFILES(X86)\\Chromium\\Application\\chrome.exe"
			, r"LOCALAPPDATA\\Chromium\\Application\\chrome.exe"
			, r"PROGRAMW6432\\Chromium\\Application\\chrome.exe"
		))
	
	def make_options(self):
		options = ChromiumOptions()
		options.page_load_strategy = CONFIG.PAGE_LOAD_STRATEGY.lower()
		options.add_experimental_option("excludeSwitches", ["enable-logging", "enable-automation"])
		options.add_experimental_option("useAutomationExtension", False)
		
		platform = get_platform()
		if platform == "linux64":
			user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s.0.0 Safari/537.36"
		elif platform == "mac-x64":
			user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s.0.0 Safari/537.36"
		else:
			user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s.0.0 Safari/537.36"
		options.add_argument("--user-agent='%s'"%(user_agent % self.short_version))
		
		options.add_argument("--no-sandbox")
		options.add_argument("--no-crash-upload")
		options.add_argument("--allow-insecure-localhost")
		options.add_argument("--ignore-certificate-errors")
		options.add_argument("--reduce-security-for-testing")
		options.add_argument("--allow-running-insecure-content")
		options.add_argument("--ignore-urlfetcher-cert-requests")
		
		options.add_argument("--lang="+CONFIG.BROWSER_LANG)
		options.add_argument("--accept-lang="+CONFIG.BROWSER_LANG)
		
		options.add_argument("--disable-infobars")
		options.add_argument("--disable-extensions")
		options.add_argument("--disable-notifications")
		options.add_argument("--disable-dev-shm-usage")
		options.add_argument("--disable-popup-blocking")
		options.add_argument("--disable-crash-reporter")
		options.add_argument("--disable-smooth-scrolling")
		options.add_argument("--disable-plugins-discovery")
		options.add_argument("--disable-oopr-debug-crash-dump")
		options.add_argument("--disable-blink-features=AutomationControlled")
		
		if self.enable_logs:
			options.set_capability("goog:loggingPrefs", {
				LOG_TYPES.BROWSER.lower()      : CONFIG.LOG_LEVEL
				, LOG_TYPES.CLIENT.lower()     : CONFIG.LOG_LEVEL
				, LOG_TYPES.DRIVER.lower()     : CONFIG.LOG_LEVEL
				, LOG_TYPES.SERVER.lower()     : CONFIG.LOG_LEVEL
				, LOG_TYPES.PROFILER.lower()   : CONFIG.LOG_LEVEL
				, LOG_TYPES.PERFORMANCE.lower(): CONFIG.LOG_LEVEL
			})
		
		prefs = {
			"intl.accept_languages": CONFIG.BROWSER_LANG
			, "intl.selected_languages": CONFIG.BROWSER_LANG
		}
		if self.download_dir:
			options.add_argument("--disable-features=InsecureDownloadWarnings,DownloadBubble,DownloadBubbleV2")
			prefs.update({
				"profile.default_content_settings.popups": 0
				, "download.prompt_for_download": False
				, "download.directory_upgrade": True
				, "disable-popup-blocking": True
				, "safebrowsing.enabled": True
				, "plugins.always_open_pdf_externally": True
				, "plugins.plugins_disabled": ["Chrome PDF Viewer"]
				, "profile.default_content_setting_values.automatic_downloads": 1
			})
			options.enable_downloads = True
			if not self.is_local_browser:
				options.set_capability("se:downloadsEnabled", True)
			else:
				prefs["download.default_directory"] = self.download_dir
			if CONFIG.BASE_URL:
				options.add_argument("--unsafely-treat-insecure-origin-as-secure="+CONFIG.BASE_URL)
			options.add_argument("--allow-running-insecure-content")
		else:
			options.enable_downloads = False
			options.set_capability("se:downloadsEnabled", False)
			if CONFIG.INCOGNITO:
				options.add_argument("incognito")
				options.add_argument("--disable-blink-features=AutomationControlled")
		options.add_experimental_option("prefs", prefs)
		
		if self.cache_dir and not CONFIG.INCOGNITO:
			options.add_argument("--disk-cache-dir="+self.cache_dir)
		else:
			options.add_argument("--disable-cache")
			options.add_argument("--disk-cache-size=0")
			options.add_argument("--media-cache-size=0")
			options.add_argument("--disable-application-cache")
		if CONFIG.PROXY:
			options.add_argument("--proxy-server="+CONFIG.PROXY)
		if self.profile_dir:
			options.add_argument("--user-data-dir="+self.profile_dir)
			options.add_argument("--allow-profiles-outside-user-dir")
			options.add_argument("--enable-profile-shortcut-manager")
			options.add_argument("--profile-directory=Default")
		if CONFIG.HEADLESS:
			options.add_argument("--headless=new")
			
			options.add_argument("--silent")
			options.add_argument("--disable-gpu")
			options.add_argument("--hide-scrollbars")
			options.add_argument("--disable-low-res-tiling")
			options.add_argument("--disable-renderer-backgrounding")
			options.add_argument("--disable-background-timer-throttling")
			options.add_argument("--disable-backgrounding-occluded-windows")
			options.add_argument("--disable-client-side-phishing-detection")
		
		if self.is_local_browser:
			if self.binary_location:
				options.binary_location = self.binary_location
		else:
			options.set_capability("browserName", self.browser_name)
			options.set_capability("browserVersion", self.version)
			options.set_capability("acceptInsecureCerts", True)
		return options
	
	def make_service(self):
		"""
		Возвращает объект обслуживания
		"""
		return ChromiumService(self.driver_path)
	
	@property
	def web_driver_class(self):
		return ChromiumDriver
	
	@property
	def enable_logs(self):
		"""
		Возвращает True если поддерживается логирование
		"""
		return True
	
	@property
	def user_version(self):
		return CONFIG.CHROMIUM_VERSION
	
	@property
	def user_local_path(self):
		"""
		Путь к исполняемому файлу браузера указанный пользователем
		"""
		return CONFIG.CHROMIUM_LOCAL_PATH
	
	@property
	def browser_name(self):
		"""
		Возвращает имя браузера
		"""
		return "chromium"
	
	@property
	def driver_path(self):
		"""
		Возвращает путь к файлу драйвера
		"""
		return get_chromedriver(self.version, self.short_version, self.browser_name)

ItemConfig.registrator(
	ItemConfig("CHROMIUM_VERSION", str, "", "CHROMIUM: Версия chromium")
	, ItemConfig("CHROMIUM_LOCAL_PATH", str, "", "CHROMIUM: Путь к исполняемому файлу chromium")
)
