#
# Copyright (c) Daniel Sheffield 2023
#
# All rights reserved
#
# THIS SOFTWARE IS PROVIDED AS IS WITHOUT WARRANTY

from pytest import mark, raises
from bottle import HTTPError
from app.rest.validate import validate_url

@mark.parametrize('url, expected', [
    ['file:///',]*2,
    ['file:///a/b/c',]*2,
    ['https://shandan.one',]*2,
    ['https://www.shandan.one',]*2,
    ['https://www.shandan.one/clip?id=123',]*2,
    
    # empty query
    ['https://www.shandan.one?', 'https://www.shandan.one',],

    # empty fragment
    ['https://www.shandan.one/clip?id=123#', 'https://www.shandan.one/clip?id=123',],

    # no double slash
    #['file:/a/b/c', (HTTPError, ""),],
    #['file:/abc', (HTTPError, ""),],

    # no scheme
    ['/a/b/c', (HTTPError, 400, "URL has no scheme"),],

    # no file path scheme
    ['file:', (HTTPError, 400, "File URL has no path"),],
    
    # no HTTPS domain
    #['https://abc?id=1:', (HTTPError, 400, "HTTP(S) URL has no netloc"),],
    
    # conecutive dots
    #['https://shandan.one/abc..id', 'https://shandan.one/abc..id',],

    # unescaped char in reg_name
    # TODO: should be invalid because netloc must be a domain name or ip ?
    ['https://🌚.shandan.one', 'https://%F0%9F%8C%9A.shandan.one',],

    # @ in user_info not allowed
    # TODO: check this - final @ should not be encoded ?
    ['https://user@mail@www.shandan.one','https://user%40mail@www.shandan.one'],

    # delimiters
    # TODO: should < be translated to %3C ?
    ['https://www.shandan.one?a<b', 'https://www.shandan.one?a<b'],

    # more delimiters
    ['https://www.shandan.one/clip?proportion=69%', 'https://www.shandan.one/clip?proportion=69%'],

    # fragment before end of reference URI
    ['https://www.shandan.one/tiny#url?id=123', 'https://www.shandan.one/tiny#url?id=123'],
])
def test_validate_url_invalid(url: str, expected: str):
    if isinstance(expected, tuple):
        exp_exception, *ex_args = expected
    else:
        exp_exception = None
    
    if not exp_exception:
        assert validate_url(url) == expected
        return

    with raises(exp_exception) as ex:
        validate_url(url)
    
    assert list(ex.value.args) == ex_args