# noinspection PyPep8
# noinspection PyArgumentList

"""
AUTO-GENERATED BY `scripts/generate_protocol.py` using `data/browser_protocol.json`
and `data/js_protocol.json` as inputs! Please do not modify this file.
"""

import logging
from typing import Any, Optional, Union

from chromewhip.helpers import PayloadMixin, BaseEvent, ChromeTypeBase

log = logging.getLogger(__name__)
from chromewhip.protocol import debugger as Debugger
from chromewhip.protocol import dom as DOM
from chromewhip.protocol import network as Network
from chromewhip.protocol import runtime as Runtime
from chromewhip.protocol import runtime as Runtime
from chromewhip.protocol import emulation as Emulation

# FrameId: Unique frame identifier.
FrameId = str

# Frame: Information about the Frame on the page.
class Frame(ChromeTypeBase):
    def __init__(self,
                 id: Union['str'],
                 loaderId: Union['Network.LoaderId'],
                 url: Union['str'],
                 securityOrigin: Union['str'],
                 mimeType: Union['str'],
                 parentId: Optional['str'] = None,
                 name: Optional['str'] = None,
                 unreachableUrl: Optional['str'] = None,
                 ):

        self.id = id
        self.parentId = parentId
        self.loaderId = loaderId
        self.name = name
        self.url = url
        self.securityOrigin = securityOrigin
        self.mimeType = mimeType
        self.unreachableUrl = unreachableUrl


# FrameResource: Information about the Resource on the page.
class FrameResource(ChromeTypeBase):
    def __init__(self,
                 url: Union['str'],
                 type: Union['Network.ResourceType'],
                 mimeType: Union['str'],
                 lastModified: Optional['Network.TimeSinceEpoch'] = None,
                 contentSize: Optional['float'] = None,
                 failed: Optional['bool'] = None,
                 canceled: Optional['bool'] = None,
                 ):

        self.url = url
        self.type = type
        self.mimeType = mimeType
        self.lastModified = lastModified
        self.contentSize = contentSize
        self.failed = failed
        self.canceled = canceled


# FrameResourceTree: Information about the Frame hierarchy along with their cached resources.
class FrameResourceTree(ChromeTypeBase):
    def __init__(self,
                 frame: Union['Frame'],
                 resources: Union['[FrameResource]'],
                 childFrames: Optional['[FrameResourceTree]'] = None,
                 ):

        self.frame = frame
        self.childFrames = childFrames
        self.resources = resources


# FrameTree: Information about the Frame hierarchy.
class FrameTree(ChromeTypeBase):
    def __init__(self,
                 frame: Union['Frame'],
                 childFrames: Optional['[FrameTree]'] = None,
                 ):

        self.frame = frame
        self.childFrames = childFrames


# ScriptIdentifier: Unique script identifier.
ScriptIdentifier = str

# TransitionType: Transition type.
TransitionType = str

# NavigationEntry: Navigation history entry.
class NavigationEntry(ChromeTypeBase):
    def __init__(self,
                 id: Union['int'],
                 url: Union['str'],
                 userTypedURL: Union['str'],
                 title: Union['str'],
                 transitionType: Union['TransitionType'],
                 ):

        self.id = id
        self.url = url
        self.userTypedURL = userTypedURL
        self.title = title
        self.transitionType = transitionType


# ScreencastFrameMetadata: Screencast frame metadata.
class ScreencastFrameMetadata(ChromeTypeBase):
    def __init__(self,
                 offsetTop: Union['float'],
                 pageScaleFactor: Union['float'],
                 deviceWidth: Union['float'],
                 deviceHeight: Union['float'],
                 scrollOffsetX: Union['float'],
                 scrollOffsetY: Union['float'],
                 timestamp: Optional['Network.TimeSinceEpoch'] = None,
                 ):

        self.offsetTop = offsetTop
        self.pageScaleFactor = pageScaleFactor
        self.deviceWidth = deviceWidth
        self.deviceHeight = deviceHeight
        self.scrollOffsetX = scrollOffsetX
        self.scrollOffsetY = scrollOffsetY
        self.timestamp = timestamp


# DialogType: Javascript dialog type.
DialogType = str

# AppManifestError: Error while paring app manifest.
class AppManifestError(ChromeTypeBase):
    def __init__(self,
                 message: Union['str'],
                 critical: Union['int'],
                 line: Union['int'],
                 column: Union['int'],
                 ):

        self.message = message
        self.critical = critical
        self.line = line
        self.column = column


# LayoutViewport: Layout viewport position and dimensions.
class LayoutViewport(ChromeTypeBase):
    def __init__(self,
                 pageX: Union['int'],
                 pageY: Union['int'],
                 clientWidth: Union['int'],
                 clientHeight: Union['int'],
                 ):

        self.pageX = pageX
        self.pageY = pageY
        self.clientWidth = clientWidth
        self.clientHeight = clientHeight


# VisualViewport: Visual viewport position, dimensions, and scale.
class VisualViewport(ChromeTypeBase):
    def __init__(self,
                 offsetX: Union['float'],
                 offsetY: Union['float'],
                 pageX: Union['float'],
                 pageY: Union['float'],
                 clientWidth: Union['float'],
                 clientHeight: Union['float'],
                 scale: Union['float'],
                 zoom: Optional['float'] = None,
                 ):

        self.offsetX = offsetX
        self.offsetY = offsetY
        self.pageX = pageX
        self.pageY = pageY
        self.clientWidth = clientWidth
        self.clientHeight = clientHeight
        self.scale = scale
        self.zoom = zoom


# Viewport: Viewport for capturing screenshot.
class Viewport(ChromeTypeBase):
    def __init__(self,
                 x: Union['float'],
                 y: Union['float'],
                 width: Union['float'],
                 height: Union['float'],
                 scale: Union['float'],
                 ):

        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.scale = scale


# FontFamilies: Generic font families collection.
class FontFamilies(ChromeTypeBase):
    def __init__(self,
                 standard: Optional['str'] = None,
                 fixed: Optional['str'] = None,
                 serif: Optional['str'] = None,
                 sansSerif: Optional['str'] = None,
                 cursive: Optional['str'] = None,
                 fantasy: Optional['str'] = None,
                 pictograph: Optional['str'] = None,
                 ):

        self.standard = standard
        self.fixed = fixed
        self.serif = serif
        self.sansSerif = sansSerif
        self.cursive = cursive
        self.fantasy = fantasy
        self.pictograph = pictograph


# FontSizes: Default font sizes.
class FontSizes(ChromeTypeBase):
    def __init__(self,
                 standard: Optional['int'] = None,
                 fixed: Optional['int'] = None,
                 ):

        self.standard = standard
        self.fixed = fixed


# ClientNavigationReason: 
ClientNavigationReason = str

class Page(PayloadMixin):
    """ Actions and events related to the inspected page belong to the page domain.
    """
    @classmethod
    def addScriptToEvaluateOnLoad(cls,
                                  scriptSource: Union['str'],
                                  ):
        """Deprecated, please use addScriptToEvaluateOnNewDocument instead.
        :param scriptSource: 
        :type scriptSource: str
        """
        return (
            cls.build_send_payload("addScriptToEvaluateOnLoad", {
                "scriptSource": scriptSource,
            }),
            cls.convert_payload({
                "identifier": {
                    "class": ScriptIdentifier,
                    "optional": False
                },
            })
        )

    @classmethod
    def addScriptToEvaluateOnNewDocument(cls,
                                         source: Union['str'],
                                         worldName: Optional['str'] = None,
                                         ):
        """Evaluates given script in every frame upon creation (before loading frame's scripts).
        :param source: 
        :type source: str
        :param worldName: If specified, creates an isolated world with the given name and evaluates given script in it.
This world name will be used as the ExecutionContextDescription::name when the corresponding
event is emitted.
        :type worldName: str
        """
        return (
            cls.build_send_payload("addScriptToEvaluateOnNewDocument", {
                "source": source,
                "worldName": worldName,
            }),
            cls.convert_payload({
                "identifier": {
                    "class": ScriptIdentifier,
                    "optional": False
                },
            })
        )

    @classmethod
    def bringToFront(cls):
        """Brings page to front (activates tab).
        """
        return (
            cls.build_send_payload("bringToFront", {
            }),
            None
        )

    @classmethod
    def captureScreenshot(cls,
                          format: Optional['str'] = None,
                          quality: Optional['int'] = None,
                          clip: Optional['Viewport'] = None,
                          fromSurface: Optional['bool'] = None,
                          ):
        """Capture page screenshot.
        :param format: Image compression format (defaults to png).
        :type format: str
        :param quality: Compression quality from range [0..100] (jpeg only).
        :type quality: int
        :param clip: Capture the screenshot of a given region only.
        :type clip: Viewport
        :param fromSurface: Capture the screenshot from the surface, rather than the view. Defaults to true.
        :type fromSurface: bool
        """
        return (
            cls.build_send_payload("captureScreenshot", {
                "format": format,
                "quality": quality,
                "clip": clip,
                "fromSurface": fromSurface,
            }),
            cls.convert_payload({
                "data": {
                    "class": str,
                    "optional": False
                },
            })
        )

    @classmethod
    def captureSnapshot(cls,
                        format: Optional['str'] = None,
                        ):
        """Returns a snapshot of the page as a string. For MHTML format, the serialization includes
iframes, shadow DOM, external resources, and element-inline styles.
        :param format: Format (defaults to mhtml).
        :type format: str
        """
        return (
            cls.build_send_payload("captureSnapshot", {
                "format": format,
            }),
            cls.convert_payload({
                "data": {
                    "class": str,
                    "optional": False
                },
            })
        )

    @classmethod
    def clearDeviceMetricsOverride(cls):
        """Clears the overriden device metrics.
        """
        return (
            cls.build_send_payload("clearDeviceMetricsOverride", {
            }),
            None
        )

    @classmethod
    def clearDeviceOrientationOverride(cls):
        """Clears the overridden Device Orientation.
        """
        return (
            cls.build_send_payload("clearDeviceOrientationOverride", {
            }),
            None
        )

    @classmethod
    def clearGeolocationOverride(cls):
        """Clears the overriden Geolocation Position and Error.
        """
        return (
            cls.build_send_payload("clearGeolocationOverride", {
            }),
            None
        )

    @classmethod
    def createIsolatedWorld(cls,
                            frameId: Union['FrameId'],
                            worldName: Optional['str'] = None,
                            grantUniveralAccess: Optional['bool'] = None,
                            ):
        """Creates an isolated world for the given frame.
        :param frameId: Id of the frame in which the isolated world should be created.
        :type frameId: FrameId
        :param worldName: An optional name which is reported in the Execution Context.
        :type worldName: str
        :param grantUniveralAccess: Whether or not universal access should be granted to the isolated world. This is a powerful
option, use with caution.
        :type grantUniveralAccess: bool
        """
        return (
            cls.build_send_payload("createIsolatedWorld", {
                "frameId": frameId,
                "worldName": worldName,
                "grantUniveralAccess": grantUniveralAccess,
            }),
            cls.convert_payload({
                "executionContextId": {
                    "class": Runtime.ExecutionContextId,
                    "optional": False
                },
            })
        )

    @classmethod
    def deleteCookie(cls,
                     cookieName: Union['str'],
                     url: Union['str'],
                     ):
        """Deletes browser cookie with given name, domain and path.
        :param cookieName: Name of the cookie to remove.
        :type cookieName: str
        :param url: URL to match cooke domain and path.
        :type url: str
        """
        return (
            cls.build_send_payload("deleteCookie", {
                "cookieName": cookieName,
                "url": url,
            }),
            None
        )

    @classmethod
    def disable(cls):
        """Disables page domain notifications.
        """
        return (
            cls.build_send_payload("disable", {
            }),
            None
        )

    @classmethod
    def enable(cls):
        """Enables page domain notifications.
        """
        return (
            cls.build_send_payload("enable", {
            }),
            None
        )

    @classmethod
    def getAppManifest(cls):
        """
        """
        return (
            cls.build_send_payload("getAppManifest", {
            }),
            cls.convert_payload({
                "url": {
                    "class": str,
                    "optional": False
                },
                "errors": {
                    "class": [AppManifestError],
                    "optional": False
                },
                "data": {
                    "class": str,
                    "optional": True
                },
            })
        )

    @classmethod
    def getCookies(cls):
        """Returns all browser cookies. Depending on the backend support, will return detailed cookie
information in the `cookies` field.
        """
        return (
            cls.build_send_payload("getCookies", {
            }),
            cls.convert_payload({
                "cookies": {
                    "class": [Network.Cookie],
                    "optional": False
                },
            })
        )

    @classmethod
    def getFrameTree(cls):
        """Returns present frame tree structure.
        """
        return (
            cls.build_send_payload("getFrameTree", {
            }),
            cls.convert_payload({
                "frameTree": {
                    "class": FrameTree,
                    "optional": False
                },
            })
        )

    @classmethod
    def getLayoutMetrics(cls):
        """Returns metrics relating to the layouting of the page, such as viewport bounds/scale.
        """
        return (
            cls.build_send_payload("getLayoutMetrics", {
            }),
            cls.convert_payload({
                "layoutViewport": {
                    "class": LayoutViewport,
                    "optional": False
                },
                "visualViewport": {
                    "class": VisualViewport,
                    "optional": False
                },
                "contentSize": {
                    "class": DOM.Rect,
                    "optional": False
                },
            })
        )

    @classmethod
    def getNavigationHistory(cls):
        """Returns navigation history for the current page.
        """
        return (
            cls.build_send_payload("getNavigationHistory", {
            }),
            cls.convert_payload({
                "currentIndex": {
                    "class": int,
                    "optional": False
                },
                "entries": {
                    "class": [NavigationEntry],
                    "optional": False
                },
            })
        )

    @classmethod
    def resetNavigationHistory(cls):
        """Resets navigation history for the current page.
        """
        return (
            cls.build_send_payload("resetNavigationHistory", {
            }),
            None
        )

    @classmethod
    def getResourceContent(cls,
                           frameId: Union['FrameId'],
                           url: Union['str'],
                           ):
        """Returns content of the given resource.
        :param frameId: Frame id to get resource for.
        :type frameId: FrameId
        :param url: URL of the resource to get content for.
        :type url: str
        """
        return (
            cls.build_send_payload("getResourceContent", {
                "frameId": frameId,
                "url": url,
            }),
            cls.convert_payload({
                "content": {
                    "class": str,
                    "optional": False
                },
                "base64Encoded": {
                    "class": bool,
                    "optional": False
                },
            })
        )

    @classmethod
    def getResourceTree(cls):
        """Returns present frame / resource tree structure.
        """
        return (
            cls.build_send_payload("getResourceTree", {
            }),
            cls.convert_payload({
                "frameTree": {
                    "class": FrameResourceTree,
                    "optional": False
                },
            })
        )

    @classmethod
    def handleJavaScriptDialog(cls,
                               accept: Union['bool'],
                               promptText: Optional['str'] = None,
                               ):
        """Accepts or dismisses a JavaScript initiated dialog (alert, confirm, prompt, or onbeforeunload).
        :param accept: Whether to accept or dismiss the dialog.
        :type accept: bool
        :param promptText: The text to enter into the dialog prompt before accepting. Used only if this is a prompt
dialog.
        :type promptText: str
        """
        return (
            cls.build_send_payload("handleJavaScriptDialog", {
                "accept": accept,
                "promptText": promptText,
            }),
            None
        )

    @classmethod
    def navigate(cls,
                 url: Union['str'],
                 referrer: Optional['str'] = None,
                 transitionType: Optional['TransitionType'] = None,
                 frameId: Optional['FrameId'] = None,
                 ):
        """Navigates current page to the given URL.
        :param url: URL to navigate the page to.
        :type url: str
        :param referrer: Referrer URL.
        :type referrer: str
        :param transitionType: Intended transition type.
        :type transitionType: TransitionType
        :param frameId: Frame id to navigate, if not specified navigates the top frame.
        :type frameId: FrameId
        """
        return (
            cls.build_send_payload("navigate", {
                "url": url,
                "referrer": referrer,
                "transitionType": transitionType,
                "frameId": frameId,
            }),
            cls.convert_payload({
                "frameId": {
                    "class": FrameId,
                    "optional": False
                },
                "loaderId": {
                    "class": Network.LoaderId,
                    "optional": True
                },
                "errorText": {
                    "class": str,
                    "optional": True
                },
            })
        )

    @classmethod
    def navigateToHistoryEntry(cls,
                               entryId: Union['int'],
                               ):
        """Navigates current page to the given history entry.
        :param entryId: Unique id of the entry to navigate to.
        :type entryId: int
        """
        return (
            cls.build_send_payload("navigateToHistoryEntry", {
                "entryId": entryId,
            }),
            None
        )

    @classmethod
    def printToPDF(cls,
                   landscape: Optional['bool'] = None,
                   displayHeaderFooter: Optional['bool'] = None,
                   printBackground: Optional['bool'] = None,
                   scale: Optional['float'] = None,
                   paperWidth: Optional['float'] = None,
                   paperHeight: Optional['float'] = None,
                   marginTop: Optional['float'] = None,
                   marginBottom: Optional['float'] = None,
                   marginLeft: Optional['float'] = None,
                   marginRight: Optional['float'] = None,
                   pageRanges: Optional['str'] = None,
                   ignoreInvalidPageRanges: Optional['bool'] = None,
                   headerTemplate: Optional['str'] = None,
                   footerTemplate: Optional['str'] = None,
                   preferCSSPageSize: Optional['bool'] = None,
                   ):
        """Print page as PDF.
        :param landscape: Paper orientation. Defaults to false.
        :type landscape: bool
        :param displayHeaderFooter: Display header and footer. Defaults to false.
        :type displayHeaderFooter: bool
        :param printBackground: Print background graphics. Defaults to false.
        :type printBackground: bool
        :param scale: Scale of the webpage rendering. Defaults to 1.
        :type scale: float
        :param paperWidth: Paper width in inches. Defaults to 8.5 inches.
        :type paperWidth: float
        :param paperHeight: Paper height in inches. Defaults to 11 inches.
        :type paperHeight: float
        :param marginTop: Top margin in inches. Defaults to 1cm (~0.4 inches).
        :type marginTop: float
        :param marginBottom: Bottom margin in inches. Defaults to 1cm (~0.4 inches).
        :type marginBottom: float
        :param marginLeft: Left margin in inches. Defaults to 1cm (~0.4 inches).
        :type marginLeft: float
        :param marginRight: Right margin in inches. Defaults to 1cm (~0.4 inches).
        :type marginRight: float
        :param pageRanges: Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means
print all pages.
        :type pageRanges: str
        :param ignoreInvalidPageRanges: Whether to silently ignore invalid but successfully parsed page ranges, such as '3-2'.
Defaults to false.
        :type ignoreInvalidPageRanges: bool
        :param headerTemplate: HTML template for the print header. Should be valid HTML markup with following
classes used to inject printing values into them:
- `date`: formatted print date
- `title`: document title
- `url`: document location
- `pageNumber`: current page number
- `totalPages`: total pages in the document

For example, `<span class=title></span>` would generate span containing the title.
        :type headerTemplate: str
        :param footerTemplate: HTML template for the print footer. Should use the same format as the `headerTemplate`.
        :type footerTemplate: str
        :param preferCSSPageSize: Whether or not to prefer page size as defined by css. Defaults to false,
in which case the content will be scaled to fit the paper size.
        :type preferCSSPageSize: bool
        """
        return (
            cls.build_send_payload("printToPDF", {
                "landscape": landscape,
                "displayHeaderFooter": displayHeaderFooter,
                "printBackground": printBackground,
                "scale": scale,
                "paperWidth": paperWidth,
                "paperHeight": paperHeight,
                "marginTop": marginTop,
                "marginBottom": marginBottom,
                "marginLeft": marginLeft,
                "marginRight": marginRight,
                "pageRanges": pageRanges,
                "ignoreInvalidPageRanges": ignoreInvalidPageRanges,
                "headerTemplate": headerTemplate,
                "footerTemplate": footerTemplate,
                "preferCSSPageSize": preferCSSPageSize,
            }),
            cls.convert_payload({
                "data": {
                    "class": str,
                    "optional": False
                },
            })
        )

    @classmethod
    def reload(cls,
               ignoreCache: Optional['bool'] = None,
               scriptToEvaluateOnLoad: Optional['str'] = None,
               ):
        """Reloads given page optionally ignoring the cache.
        :param ignoreCache: If true, browser cache is ignored (as if the user pressed Shift+refresh).
        :type ignoreCache: bool
        :param scriptToEvaluateOnLoad: If set, the script will be injected into all frames of the inspected page after reload.
Argument will be ignored if reloading dataURL origin.
        :type scriptToEvaluateOnLoad: str
        """
        return (
            cls.build_send_payload("reload", {
                "ignoreCache": ignoreCache,
                "scriptToEvaluateOnLoad": scriptToEvaluateOnLoad,
            }),
            None
        )

    @classmethod
    def removeScriptToEvaluateOnLoad(cls,
                                     identifier: Union['ScriptIdentifier'],
                                     ):
        """Deprecated, please use removeScriptToEvaluateOnNewDocument instead.
        :param identifier: 
        :type identifier: ScriptIdentifier
        """
        return (
            cls.build_send_payload("removeScriptToEvaluateOnLoad", {
                "identifier": identifier,
            }),
            None
        )

    @classmethod
    def removeScriptToEvaluateOnNewDocument(cls,
                                            identifier: Union['ScriptIdentifier'],
                                            ):
        """Removes given script from the list.
        :param identifier: 
        :type identifier: ScriptIdentifier
        """
        return (
            cls.build_send_payload("removeScriptToEvaluateOnNewDocument", {
                "identifier": identifier,
            }),
            None
        )

    @classmethod
    def screencastFrameAck(cls,
                           sessionId: Union['int'],
                           ):
        """Acknowledges that a screencast frame has been received by the frontend.
        :param sessionId: Frame number.
        :type sessionId: int
        """
        return (
            cls.build_send_payload("screencastFrameAck", {
                "sessionId": sessionId,
            }),
            None
        )

    @classmethod
    def searchInResource(cls,
                         frameId: Union['FrameId'],
                         url: Union['str'],
                         query: Union['str'],
                         caseSensitive: Optional['bool'] = None,
                         isRegex: Optional['bool'] = None,
                         ):
        """Searches for given string in resource content.
        :param frameId: Frame id for resource to search in.
        :type frameId: FrameId
        :param url: URL of the resource to search in.
        :type url: str
        :param query: String to search for.
        :type query: str
        :param caseSensitive: If true, search is case sensitive.
        :type caseSensitive: bool
        :param isRegex: If true, treats string parameter as regex.
        :type isRegex: bool
        """
        return (
            cls.build_send_payload("searchInResource", {
                "frameId": frameId,
                "url": url,
                "query": query,
                "caseSensitive": caseSensitive,
                "isRegex": isRegex,
            }),
            cls.convert_payload({
                "result": {
                    "class": [Debugger.SearchMatch],
                    "optional": False
                },
            })
        )

    @classmethod
    def setAdBlockingEnabled(cls,
                             enabled: Union['bool'],
                             ):
        """Enable Chrome's experimental ad filter on all sites.
        :param enabled: Whether to block ads.
        :type enabled: bool
        """
        return (
            cls.build_send_payload("setAdBlockingEnabled", {
                "enabled": enabled,
            }),
            None
        )

    @classmethod
    def setBypassCSP(cls,
                     enabled: Union['bool'],
                     ):
        """Enable page Content Security Policy by-passing.
        :param enabled: Whether to bypass page CSP.
        :type enabled: bool
        """
        return (
            cls.build_send_payload("setBypassCSP", {
                "enabled": enabled,
            }),
            None
        )

    @classmethod
    def setDeviceMetricsOverride(cls,
                                 width: Union['int'],
                                 height: Union['int'],
                                 deviceScaleFactor: Union['float'],
                                 mobile: Union['bool'],
                                 scale: Optional['float'] = None,
                                 screenWidth: Optional['int'] = None,
                                 screenHeight: Optional['int'] = None,
                                 positionX: Optional['int'] = None,
                                 positionY: Optional['int'] = None,
                                 dontSetVisibleSize: Optional['bool'] = None,
                                 screenOrientation: Optional['Emulation.ScreenOrientation'] = None,
                                 viewport: Optional['Viewport'] = None,
                                 ):
        """Overrides the values of device screen dimensions (window.screen.width, window.screen.height,
window.innerWidth, window.innerHeight, and "device-width"/"device-height"-related CSS media
query results).
        :param width: Overriding width value in pixels (minimum 0, maximum 10000000). 0 disables the override.
        :type width: int
        :param height: Overriding height value in pixels (minimum 0, maximum 10000000). 0 disables the override.
        :type height: int
        :param deviceScaleFactor: Overriding device scale factor value. 0 disables the override.
        :type deviceScaleFactor: float
        :param mobile: Whether to emulate mobile device. This includes viewport meta tag, overlay scrollbars, text
autosizing and more.
        :type mobile: bool
        :param scale: Scale to apply to resulting view image.
        :type scale: float
        :param screenWidth: Overriding screen width value in pixels (minimum 0, maximum 10000000).
        :type screenWidth: int
        :param screenHeight: Overriding screen height value in pixels (minimum 0, maximum 10000000).
        :type screenHeight: int
        :param positionX: Overriding view X position on screen in pixels (minimum 0, maximum 10000000).
        :type positionX: int
        :param positionY: Overriding view Y position on screen in pixels (minimum 0, maximum 10000000).
        :type positionY: int
        :param dontSetVisibleSize: Do not set visible view size, rely upon explicit setVisibleSize call.
        :type dontSetVisibleSize: bool
        :param screenOrientation: Screen orientation override.
        :type screenOrientation: Emulation.ScreenOrientation
        :param viewport: The viewport dimensions and scale. If not set, the override is cleared.
        :type viewport: Viewport
        """
        return (
            cls.build_send_payload("setDeviceMetricsOverride", {
                "width": width,
                "height": height,
                "deviceScaleFactor": deviceScaleFactor,
                "mobile": mobile,
                "scale": scale,
                "screenWidth": screenWidth,
                "screenHeight": screenHeight,
                "positionX": positionX,
                "positionY": positionY,
                "dontSetVisibleSize": dontSetVisibleSize,
                "screenOrientation": screenOrientation,
                "viewport": viewport,
            }),
            None
        )

    @classmethod
    def setDeviceOrientationOverride(cls,
                                     alpha: Union['float'],
                                     beta: Union['float'],
                                     gamma: Union['float'],
                                     ):
        """Overrides the Device Orientation.
        :param alpha: Mock alpha
        :type alpha: float
        :param beta: Mock beta
        :type beta: float
        :param gamma: Mock gamma
        :type gamma: float
        """
        return (
            cls.build_send_payload("setDeviceOrientationOverride", {
                "alpha": alpha,
                "beta": beta,
                "gamma": gamma,
            }),
            None
        )

    @classmethod
    def setFontFamilies(cls,
                        fontFamilies: Union['FontFamilies'],
                        ):
        """Set generic font families.
        :param fontFamilies: Specifies font families to set. If a font family is not specified, it won't be changed.
        :type fontFamilies: FontFamilies
        """
        return (
            cls.build_send_payload("setFontFamilies", {
                "fontFamilies": fontFamilies,
            }),
            None
        )

    @classmethod
    def setFontSizes(cls,
                     fontSizes: Union['FontSizes'],
                     ):
        """Set default font sizes.
        :param fontSizes: Specifies font sizes to set. If a font size is not specified, it won't be changed.
        :type fontSizes: FontSizes
        """
        return (
            cls.build_send_payload("setFontSizes", {
                "fontSizes": fontSizes,
            }),
            None
        )

    @classmethod
    def setDocumentContent(cls,
                           frameId: Union['FrameId'],
                           html: Union['str'],
                           ):
        """Sets given markup as the document's HTML.
        :param frameId: Frame id to set HTML for.
        :type frameId: FrameId
        :param html: HTML content to set.
        :type html: str
        """
        return (
            cls.build_send_payload("setDocumentContent", {
                "frameId": frameId,
                "html": html,
            }),
            None
        )

    @classmethod
    def setDownloadBehavior(cls,
                            behavior: Union['str'],
                            downloadPath: Optional['str'] = None,
                            ):
        """Set the behavior when downloading a file.
        :param behavior: Whether to allow all or deny all download requests, or use default Chrome behavior if
available (otherwise deny).
        :type behavior: str
        :param downloadPath: The default path to save downloaded files to. This is requred if behavior is set to 'allow'
        :type downloadPath: str
        """
        return (
            cls.build_send_payload("setDownloadBehavior", {
                "behavior": behavior,
                "downloadPath": downloadPath,
            }),
            None
        )

    @classmethod
    def setGeolocationOverride(cls,
                               latitude: Optional['float'] = None,
                               longitude: Optional['float'] = None,
                               accuracy: Optional['float'] = None,
                               ):
        """Overrides the Geolocation Position or Error. Omitting any of the parameters emulates position
unavailable.
        :param latitude: Mock latitude
        :type latitude: float
        :param longitude: Mock longitude
        :type longitude: float
        :param accuracy: Mock accuracy
        :type accuracy: float
        """
        return (
            cls.build_send_payload("setGeolocationOverride", {
                "latitude": latitude,
                "longitude": longitude,
                "accuracy": accuracy,
            }),
            None
        )

    @classmethod
    def setLifecycleEventsEnabled(cls,
                                  enabled: Union['bool'],
                                  ):
        """Controls whether page will emit lifecycle events.
        :param enabled: If true, starts emitting lifecycle events.
        :type enabled: bool
        """
        return (
            cls.build_send_payload("setLifecycleEventsEnabled", {
                "enabled": enabled,
            }),
            None
        )

    @classmethod
    def setTouchEmulationEnabled(cls,
                                 enabled: Union['bool'],
                                 configuration: Optional['str'] = None,
                                 ):
        """Toggles mouse event-based touch event emulation.
        :param enabled: Whether the touch event emulation should be enabled.
        :type enabled: bool
        :param configuration: Touch/gesture events configuration. Default: current platform.
        :type configuration: str
        """
        return (
            cls.build_send_payload("setTouchEmulationEnabled", {
                "enabled": enabled,
                "configuration": configuration,
            }),
            None
        )

    @classmethod
    def startScreencast(cls,
                        format: Optional['str'] = None,
                        quality: Optional['int'] = None,
                        maxWidth: Optional['int'] = None,
                        maxHeight: Optional['int'] = None,
                        everyNthFrame: Optional['int'] = None,
                        ):
        """Starts sending each frame using the `screencastFrame` event.
        :param format: Image compression format.
        :type format: str
        :param quality: Compression quality from range [0..100].
        :type quality: int
        :param maxWidth: Maximum screenshot width.
        :type maxWidth: int
        :param maxHeight: Maximum screenshot height.
        :type maxHeight: int
        :param everyNthFrame: Send every n-th frame.
        :type everyNthFrame: int
        """
        return (
            cls.build_send_payload("startScreencast", {
                "format": format,
                "quality": quality,
                "maxWidth": maxWidth,
                "maxHeight": maxHeight,
                "everyNthFrame": everyNthFrame,
            }),
            None
        )

    @classmethod
    def stopLoading(cls):
        """Force the page stop all navigations and pending resource fetches.
        """
        return (
            cls.build_send_payload("stopLoading", {
            }),
            None
        )

    @classmethod
    def crash(cls):
        """Crashes renderer on the IO thread, generates minidumps.
        """
        return (
            cls.build_send_payload("crash", {
            }),
            None
        )

    @classmethod
    def close(cls):
        """Tries to close page, running its beforeunload hooks, if any.
        """
        return (
            cls.build_send_payload("close", {
            }),
            None
        )

    @classmethod
    def setWebLifecycleState(cls,
                             state: Union['str'],
                             ):
        """Tries to update the web lifecycle state of the page.
It will transition the page to the given state according to:
https://github.com/WICG/web-lifecycle/
        :param state: Target lifecycle state
        :type state: str
        """
        return (
            cls.build_send_payload("setWebLifecycleState", {
                "state": state,
            }),
            None
        )

    @classmethod
    def stopScreencast(cls):
        """Stops sending each frame in the `screencastFrame`.
        """
        return (
            cls.build_send_payload("stopScreencast", {
            }),
            None
        )

    @classmethod
    def setProduceCompilationCache(cls,
                                   enabled: Union['bool'],
                                   ):
        """Forces compilation cache to be generated for every subresource script.
        :param enabled: 
        :type enabled: bool
        """
        return (
            cls.build_send_payload("setProduceCompilationCache", {
                "enabled": enabled,
            }),
            None
        )

    @classmethod
    def addCompilationCache(cls,
                            url: Union['str'],
                            data: Union['str'],
                            ):
        """Seeds compilation cache for given url. Compilation cache does not survive
cross-process navigation.
        :param url: 
        :type url: str
        :param data: Base64-encoded data
        :type data: str
        """
        return (
            cls.build_send_payload("addCompilationCache", {
                "url": url,
                "data": data,
            }),
            None
        )

    @classmethod
    def clearCompilationCache(cls):
        """Clears seeded compilation cache.
        """
        return (
            cls.build_send_payload("clearCompilationCache", {
            }),
            None
        )

    @classmethod
    def generateTestReport(cls,
                           message: Union['str'],
                           group: Optional['str'] = None,
                           ):
        """Generates a report for testing.
        :param message: Message to be displayed in the report.
        :type message: str
        :param group: Specifies the endpoint group to deliver the report to.
        :type group: str
        """
        return (
            cls.build_send_payload("generateTestReport", {
                "message": message,
                "group": group,
            }),
            None
        )

    @classmethod
    def waitForDebugger(cls):
        """Pauses page execution. Can be resumed using generic Runtime.runIfWaitingForDebugger.
        """
        return (
            cls.build_send_payload("waitForDebugger", {
            }),
            None
        )



class DomContentEventFiredEvent(BaseEvent):

    js_name = 'Page.domContentEventFired'
    hashable = []
    is_hashable = False

    def __init__(self,
                 timestamp: Union['Network.MonotonicTime', dict],
                 ):
        if isinstance(timestamp, dict):
            timestamp = Network.MonotonicTime(**timestamp)
        self.timestamp = timestamp

    @classmethod
    def build_hash(cls):
        raise ValueError('Unable to build hash for non-hashable type')


class FrameAttachedEvent(BaseEvent):

    js_name = 'Page.frameAttached'
    hashable = ['parentFrameId', 'frameId']
    is_hashable = True

    def __init__(self,
                 frameId: Union['FrameId', dict],
                 parentFrameId: Union['FrameId', dict],
                 stack: Union['Runtime.StackTrace', dict, None] = None,
                 ):
        if isinstance(frameId, dict):
            frameId = FrameId(**frameId)
        self.frameId = frameId
        if isinstance(parentFrameId, dict):
            parentFrameId = FrameId(**parentFrameId)
        self.parentFrameId = parentFrameId
        if isinstance(stack, dict):
            stack = Runtime.StackTrace(**stack)
        self.stack = stack

    @classmethod
    def build_hash(cls, parentFrameId, frameId):
        kwargs = locals()
        kwargs.pop('cls')
        serialized_id_params = ','.join(['='.join([p, str(v)]) for p, v in kwargs.items()])
        h = '{}:{}'.format(cls.js_name, serialized_id_params)
        log.debug('generated hash = %s' % h)
        return h


class FrameClearedScheduledNavigationEvent(BaseEvent):

    js_name = 'Page.frameClearedScheduledNavigation'
    hashable = ['frameId']
    is_hashable = True

    def __init__(self,
                 frameId: Union['FrameId', dict],
                 ):
        if isinstance(frameId, dict):
            frameId = FrameId(**frameId)
        self.frameId = frameId

    @classmethod
    def build_hash(cls, frameId):
        kwargs = locals()
        kwargs.pop('cls')
        serialized_id_params = ','.join(['='.join([p, str(v)]) for p, v in kwargs.items()])
        h = '{}:{}'.format(cls.js_name, serialized_id_params)
        log.debug('generated hash = %s' % h)
        return h


class FrameDetachedEvent(BaseEvent):

    js_name = 'Page.frameDetached'
    hashable = ['frameId']
    is_hashable = True

    def __init__(self,
                 frameId: Union['FrameId', dict],
                 ):
        if isinstance(frameId, dict):
            frameId = FrameId(**frameId)
        self.frameId = frameId

    @classmethod
    def build_hash(cls, frameId):
        kwargs = locals()
        kwargs.pop('cls')
        serialized_id_params = ','.join(['='.join([p, str(v)]) for p, v in kwargs.items()])
        h = '{}:{}'.format(cls.js_name, serialized_id_params)
        log.debug('generated hash = %s' % h)
        return h


class FrameNavigatedEvent(BaseEvent):

    js_name = 'Page.frameNavigated'
    hashable = ['frameId']
    is_hashable = True

    def __init__(self,
                 frame: Union['Frame', dict],
                 ):
        if isinstance(frame, dict):
            frame = Frame(**frame)
        self.frame = frame

    @classmethod
    def build_hash(cls, frameId):
        kwargs = locals()
        kwargs.pop('cls')
        serialized_id_params = ','.join(['='.join([p, str(v)]) for p, v in kwargs.items()])
        h = '{}:{}'.format(cls.js_name, serialized_id_params)
        log.debug('generated hash = %s' % h)
        return h


class FrameResizedEvent(BaseEvent):

    js_name = 'Page.frameResized'
    hashable = []
    is_hashable = False

    def __init__(self):
        pass

    @classmethod
    def build_hash(cls):
        raise ValueError('Unable to build hash for non-hashable type')


class FrameRequestedNavigationEvent(BaseEvent):

    js_name = 'Page.frameRequestedNavigation'
    hashable = ['frameId']
    is_hashable = True

    def __init__(self,
                 frameId: Union['FrameId', dict],
                 reason: Union['ClientNavigationReason', dict],
                 url: Union['str', dict],
                 ):
        if isinstance(frameId, dict):
            frameId = FrameId(**frameId)
        self.frameId = frameId
        if isinstance(reason, dict):
            reason = ClientNavigationReason(**reason)
        self.reason = reason
        if isinstance(url, dict):
            url = str(**url)
        self.url = url

    @classmethod
    def build_hash(cls, frameId):
        kwargs = locals()
        kwargs.pop('cls')
        serialized_id_params = ','.join(['='.join([p, str(v)]) for p, v in kwargs.items()])
        h = '{}:{}'.format(cls.js_name, serialized_id_params)
        log.debug('generated hash = %s' % h)
        return h


class FrameScheduledNavigationEvent(BaseEvent):

    js_name = 'Page.frameScheduledNavigation'
    hashable = ['frameId']
    is_hashable = True

    def __init__(self,
                 frameId: Union['FrameId', dict],
                 delay: Union['float', dict],
                 reason: Union['str', dict],
                 url: Union['str', dict],
                 ):
        if isinstance(frameId, dict):
            frameId = FrameId(**frameId)
        self.frameId = frameId
        if isinstance(delay, dict):
            delay = float(**delay)
        self.delay = delay
        if isinstance(reason, dict):
            reason = str(**reason)
        self.reason = reason
        if isinstance(url, dict):
            url = str(**url)
        self.url = url

    @classmethod
    def build_hash(cls, frameId):
        kwargs = locals()
        kwargs.pop('cls')
        serialized_id_params = ','.join(['='.join([p, str(v)]) for p, v in kwargs.items()])
        h = '{}:{}'.format(cls.js_name, serialized_id_params)
        log.debug('generated hash = %s' % h)
        return h


class FrameStartedLoadingEvent(BaseEvent):

    js_name = 'Page.frameStartedLoading'
    hashable = ['frameId']
    is_hashable = True

    def __init__(self,
                 frameId: Union['FrameId', dict],
                 ):
        if isinstance(frameId, dict):
            frameId = FrameId(**frameId)
        self.frameId = frameId

    @classmethod
    def build_hash(cls, frameId):
        kwargs = locals()
        kwargs.pop('cls')
        serialized_id_params = ','.join(['='.join([p, str(v)]) for p, v in kwargs.items()])
        h = '{}:{}'.format(cls.js_name, serialized_id_params)
        log.debug('generated hash = %s' % h)
        return h


class FrameStoppedLoadingEvent(BaseEvent):

    js_name = 'Page.frameStoppedLoading'
    hashable = ['frameId']
    is_hashable = True

    def __init__(self,
                 frameId: Union['FrameId', dict],
                 ):
        if isinstance(frameId, dict):
            frameId = FrameId(**frameId)
        self.frameId = frameId

    @classmethod
    def build_hash(cls, frameId):
        kwargs = locals()
        kwargs.pop('cls')
        serialized_id_params = ','.join(['='.join([p, str(v)]) for p, v in kwargs.items()])
        h = '{}:{}'.format(cls.js_name, serialized_id_params)
        log.debug('generated hash = %s' % h)
        return h


class InterstitialHiddenEvent(BaseEvent):

    js_name = 'Page.interstitialHidden'
    hashable = []
    is_hashable = False

    def __init__(self):
        pass

    @classmethod
    def build_hash(cls):
        raise ValueError('Unable to build hash for non-hashable type')


class InterstitialShownEvent(BaseEvent):

    js_name = 'Page.interstitialShown'
    hashable = []
    is_hashable = False

    def __init__(self):
        pass

    @classmethod
    def build_hash(cls):
        raise ValueError('Unable to build hash for non-hashable type')


class JavascriptDialogClosedEvent(BaseEvent):

    js_name = 'Page.javascriptDialogClosed'
    hashable = []
    is_hashable = False

    def __init__(self,
                 result: Union['bool', dict],
                 userInput: Union['str', dict],
                 ):
        if isinstance(result, dict):
            result = bool(**result)
        self.result = result
        if isinstance(userInput, dict):
            userInput = str(**userInput)
        self.userInput = userInput

    @classmethod
    def build_hash(cls):
        raise ValueError('Unable to build hash for non-hashable type')


class JavascriptDialogOpeningEvent(BaseEvent):

    js_name = 'Page.javascriptDialogOpening'
    hashable = []
    is_hashable = False

    def __init__(self,
                 url: Union['str', dict],
                 message: Union['str', dict],
                 type: Union['DialogType', dict],
                 hasBrowserHandler: Union['bool', dict],
                 defaultPrompt: Union['str', dict, None] = None,
                 ):
        if isinstance(url, dict):
            url = str(**url)
        self.url = url
        if isinstance(message, dict):
            message = str(**message)
        self.message = message
        if isinstance(type, dict):
            type = DialogType(**type)
        self.type = type
        if isinstance(hasBrowserHandler, dict):
            hasBrowserHandler = bool(**hasBrowserHandler)
        self.hasBrowserHandler = hasBrowserHandler
        if isinstance(defaultPrompt, dict):
            defaultPrompt = str(**defaultPrompt)
        self.defaultPrompt = defaultPrompt

    @classmethod
    def build_hash(cls):
        raise ValueError('Unable to build hash for non-hashable type')


class LifecycleEventEvent(BaseEvent):

    js_name = 'Page.lifecycleEvent'
    hashable = ['loaderId', 'frameId']
    is_hashable = True

    def __init__(self,
                 frameId: Union['FrameId', dict],
                 loaderId: Union['Network.LoaderId', dict],
                 name: Union['str', dict],
                 timestamp: Union['Network.MonotonicTime', dict],
                 ):
        if isinstance(frameId, dict):
            frameId = FrameId(**frameId)
        self.frameId = frameId
        if isinstance(loaderId, dict):
            loaderId = Network.LoaderId(**loaderId)
        self.loaderId = loaderId
        if isinstance(name, dict):
            name = str(**name)
        self.name = name
        if isinstance(timestamp, dict):
            timestamp = Network.MonotonicTime(**timestamp)
        self.timestamp = timestamp

    @classmethod
    def build_hash(cls, loaderId, frameId):
        kwargs = locals()
        kwargs.pop('cls')
        serialized_id_params = ','.join(['='.join([p, str(v)]) for p, v in kwargs.items()])
        h = '{}:{}'.format(cls.js_name, serialized_id_params)
        log.debug('generated hash = %s' % h)
        return h


class LoadEventFiredEvent(BaseEvent):

    js_name = 'Page.loadEventFired'
    hashable = []
    is_hashable = False

    def __init__(self,
                 timestamp: Union['Network.MonotonicTime', dict],
                 ):
        if isinstance(timestamp, dict):
            timestamp = Network.MonotonicTime(**timestamp)
        self.timestamp = timestamp

    @classmethod
    def build_hash(cls):
        raise ValueError('Unable to build hash for non-hashable type')


class NavigatedWithinDocumentEvent(BaseEvent):

    js_name = 'Page.navigatedWithinDocument'
    hashable = ['frameId']
    is_hashable = True

    def __init__(self,
                 frameId: Union['FrameId', dict],
                 url: Union['str', dict],
                 ):
        if isinstance(frameId, dict):
            frameId = FrameId(**frameId)
        self.frameId = frameId
        if isinstance(url, dict):
            url = str(**url)
        self.url = url

    @classmethod
    def build_hash(cls, frameId):
        kwargs = locals()
        kwargs.pop('cls')
        serialized_id_params = ','.join(['='.join([p, str(v)]) for p, v in kwargs.items()])
        h = '{}:{}'.format(cls.js_name, serialized_id_params)
        log.debug('generated hash = %s' % h)
        return h


class ScreencastFrameEvent(BaseEvent):

    js_name = 'Page.screencastFrame'
    hashable = ['sessionId']
    is_hashable = True

    def __init__(self,
                 data: Union['str', dict],
                 metadata: Union['ScreencastFrameMetadata', dict],
                 sessionId: Union['int', dict],
                 ):
        if isinstance(data, dict):
            data = str(**data)
        self.data = data
        if isinstance(metadata, dict):
            metadata = ScreencastFrameMetadata(**metadata)
        self.metadata = metadata
        if isinstance(sessionId, dict):
            sessionId = int(**sessionId)
        self.sessionId = sessionId

    @classmethod
    def build_hash(cls, sessionId):
        kwargs = locals()
        kwargs.pop('cls')
        serialized_id_params = ','.join(['='.join([p, str(v)]) for p, v in kwargs.items()])
        h = '{}:{}'.format(cls.js_name, serialized_id_params)
        log.debug('generated hash = %s' % h)
        return h


class ScreencastVisibilityChangedEvent(BaseEvent):

    js_name = 'Page.screencastVisibilityChanged'
    hashable = []
    is_hashable = False

    def __init__(self,
                 visible: Union['bool', dict],
                 ):
        if isinstance(visible, dict):
            visible = bool(**visible)
        self.visible = visible

    @classmethod
    def build_hash(cls):
        raise ValueError('Unable to build hash for non-hashable type')


class WindowOpenEvent(BaseEvent):

    js_name = 'Page.windowOpen'
    hashable = []
    is_hashable = False

    def __init__(self,
                 url: Union['str', dict],
                 windowName: Union['str', dict],
                 windowFeatures: Union['[]', dict],
                 userGesture: Union['bool', dict],
                 ):
        if isinstance(url, dict):
            url = str(**url)
        self.url = url
        if isinstance(windowName, dict):
            windowName = str(**windowName)
        self.windowName = windowName
        if isinstance(windowFeatures, dict):
            windowFeatures = [](**windowFeatures)
        self.windowFeatures = windowFeatures
        if isinstance(userGesture, dict):
            userGesture = bool(**userGesture)
        self.userGesture = userGesture

    @classmethod
    def build_hash(cls):
        raise ValueError('Unable to build hash for non-hashable type')


class CompilationCacheProducedEvent(BaseEvent):

    js_name = 'Page.compilationCacheProduced'
    hashable = []
    is_hashable = False

    def __init__(self,
                 url: Union['str', dict],
                 data: Union['str', dict],
                 ):
        if isinstance(url, dict):
            url = str(**url)
        self.url = url
        if isinstance(data, dict):
            data = str(**data)
        self.data = data

    @classmethod
    def build_hash(cls):
        raise ValueError('Unable to build hash for non-hashable type')
