#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright 2019 Univention GmbH
#
# https://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <https://www.gnu.org/licenses/>.
#

import os
import os.path
import random
import string
import importlib
import time
import sys


test_lib = os.environ.get('UCS_TEST_LIB', 'univention.testing.apptest')
try:
	test_lib = importlib.import_module(test_lib)
except ImportError:
	print('Could not import {}. Maybe set $UCS_TEST_LIB'.format(test_lib))
	sys.exit(1)


def _login(chrome, user, password=None):
	chrome.goto_portal()
	chrome.click_portal_tile(u'Rocket.Chat')
	time.sleep(10)
	if isinstance(user, str):
		chrome.enter_input('emailOrUsername', user)
	else:
		chrome.enter_input('emailOrUsername', user.properties['username'])
	chrome.enter_input('pass', password if password else 'univention')
	chrome.click_element('.login')
	time.sleep(5)


def _logout(chrome):
	chrome.click_element('#rocket-chat > aside [data-qa="sidebar-avatar-button"]')
	time.sleep(1)
	chrome.click_element('div.rc-popover__content li i.rcx-icon--name-sign-out')


def _setup(chrome):
	rc_admin_name = 'admin'
	rc_admin_pw = 'rocket.chat'

	_login(chrome, rc_admin_name, password=rc_admin_pw)
	time.sleep(3)
	# setup may have happened already
	chrome.click_element('form.SetupWizard__Step.SetupWizard__Step--active > div > button')
	time.sleep(2)
	chrome.click_element('form.SetupWizard__Step.SetupWizard__Step--active > div > button[type="submit"]')
	time.sleep(2)
	chrome.click_element('.SetupWizard__RegisterServerStep-option--selected')
	chrome.click_element('input[name=agreeTermsAndPrivacy] + i.rcx-check-box__fake')
	chrome.click_element('form.SetupWizard__Step.SetupWizard__Step--active > div > button[type="submit"]')
	time.sleep(2)
	chrome.click_element('button[data-qa=go-to-workspace]')
	time.sleep(2)
	chrome.enter_input('newPassword', 'univention')
	chrome.click_element('#login-card > div > div.submit > button')
	time.sleep(2)
	_logout(chrome)


def _send_message(chrome, message):
	# send message
	time.sleep(2)
	chrome.driver.find_elements_by_class_name('rcx-sidebar-item--clickable')[0].click()
	time.sleep(2)
	chrome.enter_input_element('main[data-qa-rc-room="GENERAL"] footer div.rc-message-box textarea', message)
	chrome.enter_return()
	time.sleep(1)
	# test if message was sent
	element = chrome.find_first('div.messages-box')
	message_content = element.find_elements_by_xpath('//*[text()[contains(.,"%s")]]' % message)
	assert message_content, 'Test message was not properly sent'


def dont_test_setup(chrome, users):
	with chrome.capture('rocketchat_setup'):
		_setup(chrome)


def test_enabled_user(chrome, users):
	with chrome.capture('rocketchat_enabled_user'):
		# test login and sending message with enabled user
		enabled_user = users('enabled_user', {'rocketchatActivated': True, 'mailPrimaryAddress': 'enabled@user.de'})
		time.sleep(10)
		_login(chrome, enabled_user)
		test_string = ''.join(random.choice(string.ascii_lowercase) for i in range(10))
		_send_message(chrome, test_string)
		_logout(chrome)

		# test login with wrong password
		_login(chrome, enabled_user, password='wrongpw')
		try:
			# should not work
			_logout(chrome)
			raise AssertionError
		except AssertionError:
			pass

		# test login after password change
		new_password = 'Univention.1'
		enabled_user = users('enabled_user', {'rocketchatActivated': True, 'mailPrimaryAddress': 'enabled@user.de', 'password': new_password})
		_login(chrome, enabled_user, password=new_password)
		_logout(chrome)


def dont_test_disabled_user(chrome, users):
	with chrome.capture('rocketchat_disabled_user'):
		# test login with disabled user; should not work
		disabled_user = users('disabled_user', {'rocketchatActivated': False, 'mailPrimaryAddress': 'disabled@user.de'})
		_login(chrome, disabled_user)
		try:
			# should not work
			_logout(chrome)
			raise AssertionError
		except AssertionError:
			pass


if __name__ == '__main__':
	test_lib.run_test_file(__file__)