''' Handles the Window loaded message '''
import json


class WindowLoadedHandler():  # pylint: disable=too-few-public-methods
    ''' Cone Handler '''

    def __init__(self, streetsmart, settings):
        self.streetsmart = streetsmart
        self.settings = settings

    def __get_locale(self):
        """Returns a changed version of the QGIS locale

        Returned value is understood by StreetSmart
        """
        qgis_settings = self.settings.settings
        locale = qgis_settings[self.settings.LANGUAGE].value
        if not locale.startswith("en"):
            locale = locale[0:2]
        if locale not in self.settings.get_streetsmart_locales():
            locale = self.settings.get_default_streetsmart_locale()
        return locale.replace("_", "-")

    def handle(self, _):
        """ Handle Window Loaded command

        Sends the settings for the Street Smart api to the browser window
        """
        qgis_settings = self.settings.settings
        settings = {}
        userSettings = {}

        # Check if OAuth is enabled
        use_oauth = qgis_settings[self.settings.USE_OAUTH].value

        if use_oauth:
            # For OAuth, only send API key and client ID, NOT username/password
            userSettings["apiKey"] = qgis_settings[self.settings.API_KEY].value
            userSettings["useOAuth"] = True
            userSettings["clientId"] = qgis_settings[self.settings.CLIENT_ID].value
        else:
            # For basic authentication, send username and password
            userSettings["username"] = qgis_settings[self.settings.USERNAME].value
            userSettings["password"] = qgis_settings[self.settings.PASSWORD].value
            userSettings["apiKey"] = qgis_settings[self.settings.API_KEY].value
            userSettings["useOAuth"] = False

        settings["userSettings"] = userSettings

        addressSettings = {}
        addressSettings["locale"] = "en"
        addressSettings["database"] = "Nokia"
        settings["addressSettings"] = addressSettings

        configSettings = {}
        project_srs = self.streetsmart.iface.mapCanvas().mapSettings().destinationCrs().authid()
        configSettings["srs"] = project_srs  # qgis_settings[self.settings.STREETSMART_SRS].value

        locale = self.__get_locale()

        configSettings["locale"] = locale

        # Use default values if None is set (when "use default" checkbox is checked)
        config_url = qgis_settings[self.settings.CONFIGURATION_URL].value
        if config_url is None:
            config_url = qgis_settings[self.settings.CONFIGURATION_URL].default
        configSettings["configUrl"] = config_url

        streetsmart_url = qgis_settings[self.settings.STREETSMART_LOCATION].value
        if streetsmart_url is None:
            streetsmart_url = qgis_settings[self.settings.STREETSMART_LOCATION].default
        configSettings["streetsmartApiUrl"] = streetsmart_url

        settings["configSettings"] = configSettings

        message_load = json.dumps(settings)

        # Use initapi_direct for OAuth (direct loading), initapi for basic auth (localhost)
        if use_oauth:
            self.streetsmart.sendToViewer("initapi_direct|{}".format(message_load))
        else:
            self.streetsmart.sendToViewer("initapi|{}".format(message_load))
