"""Contain the AskViewTests class"""

import unittest
import os
import tempfile
import datetime
import json
import humanize

from shutil import copyfile

from pyramid import testing
from pyramid.paster import get_appsettings
from askomics.libaskomics.ParamManager import ParamManager
from askomics.libaskomics.TripleStoreExplorer import TripleStoreExplorer
from askomics.libaskomics.rdfdb.SparqlQueryBuilder import SparqlQueryBuilder
from askomics.libaskomics.rdfdb.QueryLauncher import QueryLauncher
from askomics.libaskomics.EndpointManager import EndpointManager
from askomics.ask_view import AskView
from SetupTests import SetupTests


from interface_tps_db import InterfaceTpsDb

class AskViewTests(unittest.TestCase):
    """Test for Askview

    Contain all the tests for the askView class
    """

    def setUp(self):
        """Set up the configuration to access the triplestore

        Use the config file test.virtuoso.ini to not interfere with
        production data
        """

        self.settings = get_appsettings('configs/tests.ini', name='main')
        self.settings['askomics.upload_user_data_method'] = 'insert'

        self.request = testing.DummyRequest()

        self.config = testing.setUp(request=self.request)
        s
elf.config.add_route('load_data_into_graph', '/load_data_into_gr
aph')
        self.config.scan()

        self.request.session['user_id'] = 1
        self.request.session['username'] = 'jdoe'
        self.request.session['email'] = 'jdoe@example.com'
        self.request.session['admin'] = True
        self.request.session['blocked'] = False
        self.request.session['graph'] = 'urn:sparql:test_askomics:jdoe'

        self.request.host_url = 'http://localhost:6543'

        self.request.json_body = {}

        SetupTests(self.settings, self.request.session)

        self.tps = InterfaceTpsDb(self.settings, self.request)

        self.askview = AskView(self.request)
        self.askview.settings = self.settings


    def getKeyNode(self,node):
        return node['uri']

    def test_main(self):
        import askomics
        askomics.main(self.config)

    def test_start_points(self):
        """Test the start_points method

        Insert 2 datasets and test the start points
        """

        self.tps.clean_up()

        # load a test
        timestamp_people = self.tps.load_people()
        timestamp_instruments = self.tps.load_instruments()
        data = self.askview.start_points()
        # empty tps
        self.tps.clean_up()


        expected_result = {
            'nodes': {
                self.settings['askomics.prefix']+'Instruments':
                {
                    'uri':
                    self.settings['askomics.prefix']+'Instruments',
                    'g':
                    'urn:sparql:test_askomics:jdoe:instruments_tsv_' + timestamp_instruments,
                    'public': False,
                    'label': 'Instruments',
                    'private': True,
                    'endpoint': 'http://localhost:8890/sparql'
                },
                self.settings['askomics.prefix']+'People':
                {
                    'uri':
                    self.settings['askomics.prefix']+'People',
                    'g':
                    'urn:sparql:test_askomics:jdoe:people_tsv_' + timestamp_people,
                    'public': False,
                    'label': 'People',
                    'private': True,
                    'endpoint': 'http://localhost:8890/sparql'
                }
            },
            'galaxy': False
        }

        assert len(data["nodes"]) == 2
        # data["nodes"] = sorted(data["nodes"], key=self.getKeyNode)
        # expected_result["nodes"] = sorted(
            # expected_result["nodes"], key=self.getKeyNode)
        assert expected_result["nodes"] == data["nodes"]

    def test_statistics(self):

        # empty tps
        self.tps.clean_up()

        # load a test
        timestamp_people = self.tps.load_public_people()
        timestamp_instrument = self.tps.load_instruments()
        self.askview.statistics()

    def test_add_endpoint(self):

            # empty tps
            self.tps.clean_up()
            try:
                self.askview.add_endpoint()
                assert False
            except Exception as e:
                assert True
            self.request.json_body['name'] = 'testendp'
            try:
                self.askview.add_endpoint()
                assert False
            except Exception as e:
                assert True

            self.request.json_body['url'] = 'https://dbpedia.org/sparql'
            try:
                self.askview.add_endpoint()
                assert False
            except Exception as e:
                assert True

            self.request.json_body['auth'] = 'bidon'
            try:
                self.askview.add_endpoint()
                assert False
            except Exception as e:
                assert True

            self.request.json_body['auth'] = 'basic'
            try:
               self.askview.add_endpoint()
               assert True
            except Exception as e:
               assert False

    def test_zenable_endpoint(self):

            # empty tps
            self.tps.clean_up()
            self.request.json_body['name'] = 'testendp'
            self.request.json_body['url'] = 'https://dbpedia.org/sparql'
            self.request.json_body['auth'] = 'basic'

            try:
                self.askview.add_endpoint()
                assert True
            except Exception as e:
                assert False

            try:
                self.askview.enable_endpoints()
                assert False
            except Exception as e:
                assert True

            self.request.json_body['id'] = 1
            try:
                self.askview.enable_endpoints()
                assert False
            except Exception as e:
                assert True

            self.request.json_body['enable'] = True
            try:
                self.askview.enable_endpoints()
                assert True
            except Exception as e:
                assert False
            self.request.json_body['enable'] = False
            try:
                self.askview.enable_endpoints()
                assert True
            except Exception as e:
                assert False

            self.tps.clean_up()

    def test_zdelete_endpoint(self):

            # empty tps
            self.tps.clean_up()
            self.request.json_body['name'] = 'testendp'
            self.request.json_body['url'] = 'https://dbpedia.org/sparql'
            self.request.json_body['auth'] = 'basic'

            try:
                self.askview.add_endpoint()
                assert True
            except Exception as e:
                assert False

            try:
                self.askview.delete_endpoints()
                assert False
            except Exception as e:
                assert True

            self.request.json_body['endpoints'] = 'testendp'
            try:
                self.askview.delete_endpoints()
                assert True
            except Exception as e:
                print(e)
                assert False

    def test_list_endpoint(self):

            # empty tps
            self.tps.clean_up()
            self.request.json_body['name'] = 'testendp'
            self.request.json_body['url'] = 'https://dbpedia.org/sparql'
            self.request.json_body['auth'] = 'basic'

            try:
                self.askview.add_endpoint()
                assert True
            except Exception as e:
                assert False

            self.askview.list_endpoints()

    def test_guess_csv_header_type(self):

        self.tps.clean_up()
        try:
            self.askview.guess_csv_header_type()
            assert False
        except Exception as e:
            assert True
        self.request.json_body['filename'] = 'people.tsv'
        self.askview.guess_csv_header_type()

    def test_empty_database(self):
        """Test the empty_database method

        Insert data and test empt