# -*- coding: utf-8 -*-

# -----------------------------------------------------------------------------
# Copyright (c) 2016-2017 Anaconda, Inc.
#
# May be copied and distributed freely only as part of an Anaconda or
# Miniconda installation.
# -----------------------------------------------------------------------------
"""Anaconda.org login dialogs."""

__all__ = ['AnacondaLoginPage']

import typing
from qtpy import QtWidgets
from anaconda_navigator.api.anaconda_api import AnacondaAPI
from anaconda_navigator.config import CONF, ANACONDA_ORG_BRAND
from anaconda_navigator.static.images import ANACONDA_ORG_EDITION_LOGIN_LOGO
from .base_dialogs import BaseLoginPage
from .utils import TextContainer, FORGOT_LOGIN_URL, FORGOT_PASSWORD_URL, USER_RE_VALIDATOR

ANACONDA_LOGIN_TEXT_CONTAINER = TextContainer(
    info_frame_text=(
        'Log into Anaconda.org to access private channels and packages. If you don’t have an account, click '
        '<a href="{}" style="color:#43B049;text-decoration: none">here</a>.'
    ),
    form_forgot_links_msg=(
        'Forget your <a href="{username_url}" style="color:#43B049; text-decoration:none">username</a> or '
        '<a href="{password_url}" style="color:#43B049; text-decoration:none">password</a>?'
    ),
    message_box_error_text='The Anaconda.Org API domain is not specified! Please, set in preferences.',
    info_frame_logo_path=ANACONDA_ORG_EDITION_LOGIN_LOGO,
)


class AnacondaLoginPage(BaseLoginPage):

    def __init__(self, parent: typing.Optional[QtWidgets.QWidget] = None) -> None:
        """Login dialog."""
        super().__init__(AnacondaAPI(), ANACONDA_LOGIN_TEXT_CONTAINER, parent=parent)
        self.api_url_config_option = 'anaconda_api_url'
        self.brand = ANACONDA_ORG_BRAND
        self.text_login.setValidator(USER_RE_VALIDATOR)

    def update_links(self):
        """Update links."""
        anaconda_api_url = CONF.get('main', 'anaconda_api_url', self.api.client_get_api_url())

        if not anaconda_api_url:
            return

        base_url = anaconda_api_url.lower().replace('//api.', '//')

        parts = base_url.lower().split('/')
        base_url = '/'.join(parts[:-1]) if parts[-1] == 'api' else base_url

        forgot_links_updated_text = self.forgot_links.text().format(
            username_url=base_url + '/' + FORGOT_LOGIN_URL,
            password_url=base_url + '/' + FORGOT_PASSWORD_URL
        )
        info_updated_text = self.label_information.text().format(base_url)
        self.label_information.setText(info_updated_text)
        self.forgot_links.setText(forgot_links_updated_text)

        self.label_information.linkActivated.connect(lambda activated_link: self.open_url(activated_link))
        self.forgot_links.linkActivated.connect(lambda activated_link: self.open_url(activated_link))
