# -*- coding:utf-8 -*-
#
# author: philip1134
# date: 2023-02-26
#


import urllib
import miaou.logger as logger
from miaou.scanner import ScannerFactory
from miaou.specs import Specs


class Application:
    """main application"""

    def __init__(self, **attrs):
        """initializer, supported config attrs:

            - site_url: zentao site url, required
            - username: admin user name, required
            - password: admin password, required
            - dev_url: dev page url, auto generated by site url
            - scanner: scanner type, currently supported 'selenium', or
                    customized scanner instance
            - combined_print: print to one yaml or not, default is True
            - output_path: output path, default is current directory
        """

        self.site_url = attrs.get("site_url", "")
        # check out url
        if not self.site_url.endswith("/"):
            self.site_url += "/"

        self.username = attrs.get("username", "admin")
        self.password = attrs.get("password", "")

        self.dev_url = attrs.get("dev_url", None)
        if self.dev_url is None:
            self.dev_url = urllib.parse.urljoin(
                self.site_url, "dev-api.html")

        self.scanner = ScannerFactory.get(
            attrs.get("scanner", "selenium"),
            attrs.get("config", {})
        )

        self.specs = Specs()
        self.combined_print = attrs.get("combined_print", True)
        self.output_path = attrs.get("output_path", ".")

# public
    def main(self):
        """main routine"""

        # login
        self.scanner.open(
            site_url=self.site_url,
            username=self.username,
            password=self.password
        )

        # get module groups
        logger.stage("get module groups from '%s'..." % self.dev_url)
        modules = self.scanner.get_module_groups(self.dev_url)

        # get apis
        logger.stage("get apis...")
        for module_url in modules:
            self.specs.append(
                module=module_url,
                apis=self.scanner.get_apis(module_url)
            )

        # print out
        logger.stage("print specs...")
        self.specs.print(
            output_path=self.output_path,
            combined=self.combined_print,
        )

        self.scanner.close()

# end
