#!/usr/bin/python
# -*- coding: utf-8 -*-


from univention.testing.selenium import UMCSeleniumTest
from univention.config_registry import ConfigRegistry
from xvfbwrapper import Xvfb
from argparse import ArgumentParser
import univention.testing.udm as udm_test

import os
import ldap.dn
import time
import random
import string
import pytest
import selenium.common.exceptions

os.environ['UCSTEST_SELENIUM'] = 'local'
os.environ['UCSTEST_SELENIUM_BROWSER'] = 'chrome'
os.environ['PATH'] += ':/usr/lib/chromium-browser'
os.environ['LC_ALL'] = 'C'


def assert_nextclound_txtfile_exists(username, filename):
    filepath = '/var/lib/univention-appcenter/apps/nextcloud/data/nextcloud-data/{}/files/{}.txt'.format(username, filename)
    assert os.path.isfile(filepath)


def nextcloud_login(ucr, username, password, ignore_firstrunwizard=False, txt_file=None):
    hostname = '%s.%s' % (ucr.get('hostname'), ucr.get('domainname'))
    with Xvfb():
        with UMCSeleniumTest() as s:
            # login
            s.driver.get('https://%s//nextcloud' % hostname)
            s.click_text('Direct log in')
            s.enter_input('user', username)
            s.enter_input('password', password)
            s.driver.find_element_by_id('submit').submit()

            # first run wizard
            try:
                elem = s.driver.find_element_by_id('firstrunwizard')
                elem.find_element_by_xpath("//a[@class='close icon-close']").click()
                time.sleep(3)
            except Exception as exc:
                if not ignore_firstrunwizard:
                    raise(exc)

            # new txt file
            #if txt_file:
            #    s.driver.find_element_by_xpath("//a[@class='button new']").click()
            #    s.driver.find_element_by_xpath("//span[@class='icon icon-filetype-text svg']").click()
            #    new_file = s.driver.find_element_by_id('view17-input-file')
            #    new_file.send_keys(txt_file)
            #    new_file.submit()
            #    time.sleep(3)
            #    overlay = s.driver.find_element_by_id('app-content-texteditor')
            #    overlay.find_element_by_id('editor_close').click()

            # logout
            settings = s.driver.find_element_by_id('settings')
            settings.click()
            logout = s.driver.find_element_by_xpath("//li[@data-id='logout']")
            logout.click()


def get_admin_credentials(binddn, bindpwdfile):
    with open(bindpwdfile, 'r') as f:
        password = f.readline().strip()
    uid = ldap.dn.str2dn(ldap.dn.explode_rdn(binddn)[0])[0][0][1]
    return (uid, password)


def main():
    ucr = ConfigRegistry()
    ucr.load()
    usage = '%(prog)s'
    description = '%(prog)s nextcloud App test script'
    parser = ArgumentParser(usage=usage, description=description)
    parser.add_argument('--binddn', help='LDAP binddn')
    parser.add_argument('--bindpwdfile', help='LDAP binddn password file')
    args = parser.parse_args()

    # check admin account
    (admin_uid, admin_password) = get_admin_credentials(args.binddn, args.bindpwdfile)
    txt_file = 'admin-{}-file'.format(string.join(random.sample(string.lowercase, 10), ''))
    nextcloud_login(ucr, admin_uid, admin_password, ignore_firstrunwizard=True, txt_file=txt_file)
    #assert_nextclound_txtfile_exists(admin_uid, txt_file)

    # check nextcloud user
    with udm_test.UCSTestUDM() as udm:
        user1_dn, user1 = udm.create_user(nextcloudEnabled=1, password='univention')
        user2_dn, user2 = udm.create_user(nextcloudEnabled='0', password='univention')
        user3_dn, user3 = udm.create_user(nextcloudEnabled=1, password='univention')

        # login OK
        nextcloud_login(ucr, user1, 'univention')
        nextcloud_login(ucr, user3, 'univention')

        # no nextcloud user
        with pytest.raises(selenium.common.exceptions.NoSuchElementException):
            nextcloud_login(ucr, user2, 'univention')

        # password change
        udm.modify_object('users/user', dn=user3_dn, password='univention.99')
        with pytest.raises(selenium.common.exceptions.NoSuchElementException):
            nextcloud_login(ucr, user3, 'univention')
        nextcloud_login(ucr, user3, 'univention.99', ignore_firstrunwizard=True)


if __name__ == '__main__':
    main()
