# -*- coding: utf-8 -*-
#
# Copyright 2016 Continuum Analytics, Inc.
# May be copied and distributed freely only as part of an Anaconda or
# Miniconda installation.
#

"""
Anaconda Cloud login dialog.
"""

# Standard library imports
from __future__ import absolute_import, division, print_function

# Third party imports
from qtpy.QtCore import Qt, QUrl
from qtpy.QtGui import QDesktopServices
from qtpy.QtWidgets import (QApplication, QDialogButtonBox, QGridLayout,
                            QHBoxLayout, QLabel, QLineEdit, QPushButton,
                            QVBoxLayout)

# Local imports
from anaconda_navigator.api import AnacondaAPI
from anaconda_navigator.config import CONF
from anaconda_navigator.utils.analytics import GATracker
from anaconda_navigator.utils.styles import load_style_sheet
from anaconda_navigator.widgets import ButtonCancel, ButtonLabel, ButtonLink
from anaconda_navigator.widgets.dialogs import DialogBase


class AuthenticationDialog(DialogBase):
    FORGOT_USERNAME_URL = 'account/forgot_username'
    FORGOT_PASSWORD_URL = 'account/forgot_password'

    def __init__(self, api, parent=None):
        super(AuthenticationDialog, self).__init__(parent)

        self.api = api
        self._parent = parent
        self.token = None
        self.error = None
        self.tracker = GATracker()

        # Widgets
        self.label_username = QLabel('Username:')
        self.label_password = QLabel('Password:')
        self.text_username = QLineEdit()
        self.text_password = QLineEdit()
#        self.label_register_text = LabelLinks('You can register ')
        self.label_signin_text = QLabel('<hr><br><b>Already a member? '
                                        'Sign in!</b><br>')
        # For styling purposes the label next to a ButtonLink is also a button
        # so they align adequately
        self.button_register_text = ButtonLabel('You can register by '
                                                'visiting the')
        self.button_register = ButtonLink('Anaconda Cloud')
        self.button_register_after_text = ButtonLabel('website.')
        self.label_information = QLabel('''
            <strong>Anaconda Cloud</strong> is where packages, notebooks,
            and <br> environments are shared. It provides powerful <br>
            collaboration and package management for open <br>
            source and private projects.<br>
            ''')
        self.label_message = QLabel('')
        self.button_forgot_username = ButtonLink('I forgot my username')
        self.button_forgot_password = ButtonLink('I forgot my password')
        self.button_login = QPushButton('Login')
        self.button_cancel = ButtonCancel('Cancel')
        self.bbox = QDialogButtonBox(Qt.Horizontal)

        # Widgets setup
        self.bbox.addButton(self.button_cancel, QDialogButtonBox.RejectRole)
        self.bbox.addButton(self.button_login, QDialogButtonBox.AcceptRole)
        self.text_username.setAttribute(Qt.WA_MacShowFocusRect, False)
        self.text_password.setAttribute(Qt.WA_MacShowFocusRect, False)

        self.setMinimumWidth(260)
        self.setWindowTitle('Sign in')

        # This allows to completely style the dialog with css using the frame
        self.text_password.setEchoMode(QLineEdit.Password)
        self.label_message.setVisible(False)

        # Layout
        grid_layout = QGridLayout()
        grid_layout.addWidget(self.label_username, 0, 0)
        grid_layout.addWidget(self.text_username, 0, 1)
        grid_layout.addWidget(self.label_password, 1, 0)
        grid_layout.addWidget(self.text_password, 1, 1)

        main_layout = QVBoxLayout()
        main_layout.addWidget(self.label_information)

        register_layout = QHBoxLayout()
        register_layout.addWidget(self.button_register_text, 0)
        register_layout.addWidget(self.button_register, 0, Qt.AlignLeft)
        register_layout.addWidget(self.button_register_after_text, 0,
                                  Qt.AlignLeft)
        register_layout.addStretch()
        register_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.addLayout(register_layout)
        main_layout.addWidget(self.label_signin_text)
        main_layout.addLayout(grid_layout)
        main_layout.addSpacing(5)
        main_layout.addWidget(self.label_message)
        main_layout.addWidget(self.button_forgot_username, 0, Qt.AlignRight)
        main_layout.addWidget(self.button_forgot_password, 0, Qt.AlignRight)

        main_layout.addSpacing(15)
        main_layout.addWidget(self.bbox)

        self.setLayout(main_layout)

        # Signals
        self.text_username.textEdited.connect(self.check_text)
        self.text_password.textEdited.connect(self.check_text)
        self.button_login.clicked.connect(self.login)
        self.button_cancel.clicked.connect(self.reject)

        # Setup
        self.check_text()
        self.update_style_sheet()
        self.text_username.setFocus()
        self.update_links()

    def update_links(self):
        for button in [self.button_forgot_username,
                       self.button_forgot_password,
                       self.button_register]:
            try:
                button.disconnect()
            except TypeError:
                pass

        anaconda_api_url = CONF.get('main', 'anaconda_api_url', None)
        if anaconda_api_url:
            # Remove api if using a subdomain
            base_url = anaconda_api_url.lower().replace('//api.', '//')

            # Remove api if not using a subdomain
            parts = base_url.lower().split('/')
            if parts[-1] == 'api':
                base_url = '/'.join(parts[:-1])

            forgot_username_url = base_url + '/' + self.FORGOT_USERNAME_URL
            forgot_password_url = base_url + '/' + self.FORGOT_PASSWORD_URL

            self.button_register.clicked.connect(
                lambda: self.open_url(base_url))
            self.button_forgot_username.clicked.connect(
                lambda: self.open_url(forgot_username_url))
            self.button_forgot_password.clicked.connect(
                lambda: self.open_url(forgot_password_url))

    @property
    def username(self):
        return self.text_username.text()

    def update_style_sheet(self, style_sheet=None):
        if style_sheet is None:
            style_sheet = load_style_sheet()
        self.setStyleSheet(style_sheet)

    def check_text(self):
        """
        Check that `username` and `password` are not empty and disabel/enable
        buttons accordingly.
        """
        username = self.text_username.text()
        password = self.text_password.text()

        if len(username) == 0 or len(password) == 0:
            self.button_login.setDisabled(True)
        else:
            self.button_login.setDisabled(False)

    def login(self):
        self.button_login.setEnabled(False)
        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.label_message.setText('')
        worker = self.api.client_login(self.text_username.text(),
                                       self.text_password.text(),
                                       'Anaconda Navigator',
                                       '')
        worker.sig_finished.connect(self._finished)

    def _finished(self, worker, output, error):
        """
        Method called when the anaconda-client Api has finished a process
        that runs in a separate worker thread.
        """
        token = output

        if token:
            self.token = token
            self.accept()
        elif error:
            username = self.text_username.text()
            bold_username = '<b>{0}</b>'.format(username)

            # The error might come in (error_message, http_error) format
            try:
                error_message = eval(str(error))[0]
            except Exception:
                error_message = str(error)

            error_message = error_message.lower().capitalize()
            error_message = error_message.split(', ')[0]
            error_text = '<i>{0}</i>'.format(error_message)
            error_text = error_text.replace(username, bold_username)
            self.label_message.setText(error_text)
            self.label_message.setVisible(True)

            if error_message:
                domain = self.api.client_domain()
                label = '{0}/{1}: {2}'.format(domain, username,
                                              error_message.lower())
                self.tracker.track_event('authenticate', 'login failed',
                                         label=label)
                self.text_password.setFocus()
                self.text_password.selectAll()

        self.button_login.setDisabled(False)
        self.check_text()
        QApplication.restoreOverrideCursor()

    def open_url(self, url):
        self.tracker.track_event('content', 'click', url)
        QDesktopServices.openUrl(QUrl(url))


def test():
    from anaconda_navigator.utils.qthelpers import qapplication
    app = qapplication(test_time=3)
    dialog = AuthenticationDialog(AnacondaAPI())
    dialog.update_style_sheet()
    if dialog.exec_():
        print('token', dialog.token)
    app.exec_()


if __name__ == '__main__':
    test()
