import binascii
from django.conf import settings
from django.urls.base import reverse
import os

SHUFFLE_DISABLE = 0
SHUFFLE_KEEP = 1
SHUFFLE_ENABLE = 2

REPEAT_DISABLE = 0
REPEAT_ENABLE = 1

SEARCH_DISABLE = 0
SEARCH_KEEP = 1

RESP_TYPE_RAWITEM = 'raw'
RESP_TYPE_WEBNAIL = 'webnail'
RESP_TYPE_THUMBNAIL = 'thumbnail'
RESP_TYPE_USERVIEW = 'userview'
RESP_TYPE_INFOVIEW = 'infoview'
RESP_TYPE_DOWNLOAD = 'download'
RESP_TYPE_SEARCH = 'search'

DATA_TYPE_ITEM = 'item'
DATA_TYPE_SEARCH = 'search'


def __get_settings__():
    from .models import Setting
    try:
        s = Setting.objects.get(id=1)
    except Setting.DoesNotExist:
        s = Setting(id=1)
        s.save()
    return s


def suspend_public():
    return __get_settings__().suspend_puplic


def show_image():
    return __get_settings__().show_image


def show_video():
    return __get_settings__().show_video


def show_audio():
    return __get_settings__().show_audio


def show_other():
    return __get_settings__().show_other


def dict2args(d):
    if len(d) == 0:
        return ''
    al = []
    for key in d:
        if d[key] is None:
            al.append('%s' % key)
        else:
            al.append('%s=%s' % (key, d[key]))
    return '?' + '&'.join(al)


def pygal_responses_kwargs(responsetype, datatype, rel_path):
    kwargs = {'responsetype': responsetype, 'datatype': datatype}
    if rel_path:
        kwargs['rel_path'] = rel_path
    return kwargs


def url_args(request, repeat=REPEAT_DISABLE, shuffle=SHUFFLE_KEEP, search=SEARCH_DISABLE, flat=False):
    args_d = {}
    if repeat == REPEAT_ENABLE:
        args_d['repeat'] = None
    if shuffle == SHUFFLE_ENABLE:
        args_d['shuffle'] = binascii.hexlify(os.urandom(24)).decode('utf-8')
    elif shuffle == SHUFFLE_KEEP:
        shuffle_id = get_shuffle_id(request)
        if shuffle_id is not None:
            args_d['shuffle'] = shuffle_id
    if search == SEARCH_KEEP:
        search_query = get_search_query(request)
        if search_query is not None:
            args_d['q'] = search_query
    elif type(search) == str:
        args_d['q'] = search
    if flat:
        args_d['flat'] = None
    return args_d


def get_full_path(rel_path):
    return os.path.join(settings.ITEM_ROOT, rel_path.replace('/', os.path.sep))


def get_rel_path(full_path):
    if full_path.startswith(settings.ITEM_ROOT):
        return full_path[len(settings.ITEM_ROOT) + 1:].replace(os.path.sep, '/')


def set_thumbnail_size(request, value):
    request.session[settings.SESSION_KEY_THUMBNAIL_SIZE] = value


def get_thumbnail_size(request):
    return request.session.get(settings.SESSION_KEY_THUMBNAIL_SIZE, max(settings.THUMBNAIL_SIZES))


def get_thumbnail_max_size(request):
    return max(settings.THUMBNAIL_SIZES)


def set_webnail_size(request, value):
    request.session[settings.SESSION_KEY_WEBNAIL_SIZE] = value


def get_webnail_size(request):
    return request.session.get(settings.SESSION_KEY_WEBNAIL_SIZE, max(settings.WEBNAIL_SIZES))


def get_datatype(request):
    try:
        return request.META['PATH_INFO'].split('/')[3]
    except IndexError:
        return None


def get_responsetype(request):
    try:
        return request.META['PATH_INFO'].split('/')[2]
    except IndexError:
        return None


def url_download(request, rel_path, flat=False):
    return reverse('pygal-responses', kwargs=pygal_responses_kwargs(RESP_TYPE_DOWNLOAD, get_datatype(request), rel_path)) + dict2args(url_args(request, flat=flat, search=SEARCH_KEEP))


def url_helpview(request, page):
    return reverse('pygal-helpview', kwargs={'page': page})


def url_infoview(request, rel_path, repeat=REPEAT_DISABLE, shuffle=SHUFFLE_KEEP, search=SEARCH_DISABLE):
    return reverse('pygal-responses', kwargs=pygal_responses_kwargs(RESP_TYPE_INFOVIEW, get_datatype(request), rel_path)) + dict2args(url_args(request, repeat=repeat, shuffle=shuffle, search=search))


def url_item(request, rel_path):
    return reverse('pygal-responses', kwargs=pygal_responses_kwargs(RESP_TYPE_RAWITEM, DATA_TYPE_ITEM, rel_path))


def url_profile(request):
    nxt = request.GET.get('next', request.get_full_path())
    return reverse('pygal-profile') + '?next=%s' % nxt


def url_repeatview(request, rel_path):
    return url_userview(request, rel_path, repeat=REPEAT_ENABLE, search=SEARCH_KEEP) + '#openModal'


def url_search(request):
    return reverse('pygal-responses', kwargs={'responsetype': RESP_TYPE_USERVIEW, 'datatype': DATA_TYPE_SEARCH})


def url_thumbnail(request, rel_path):
    return reverse('pygal-responses', kwargs=pygal_responses_kwargs(RESP_TYPE_THUMBNAIL, DATA_TYPE_ITEM, rel_path))


def url_userview(request, rel_path, repeat=REPEAT_DISABLE, shuffle=SHUFFLE_KEEP, search=SEARCH_DISABLE):
    if shuffle in [SHUFFLE_DISABLE, SHUFFLE_ENABLE]:
        return request.META.get('PATH_INFO') + dict2args(url_args(request, repeat=repeat, shuffle=shuffle, search=search))
    return reverse('pygal-responses', kwargs=pygal_responses_kwargs(RESP_TYPE_USERVIEW, get_datatype(request), rel_path)) + dict2args(url_args(request, repeat=repeat, shuffle=shuffle, search=search))


def url_webnail(request, rel_path):
    return reverse('pygal-responses', kwargs=pygal_responses_kwargs(RESP_TYPE_WEBNAIL, DATA_TYPE_ITEM, rel_path))


def url_favouriteview(request):
    return url_search(request) + dict2args(url_args(request, repeat=REPEAT_DISABLE, shuffle=SHUFFLE_DISABLE, search='favourite_of:%s' % request.user.username))


def url_favourite_set(request, rel_path):
    nxt = request.GET.get('next', request.get_full_path())
    return reverse('pygal-setfavourite', args=(1, rel_path, )) + '?next=%s' % nxt


def url_favourite_unset(request, rel_path):
    nxt = request.GET.get('next', request.get_full_path())
    return reverse('pygal-setfavourite', args=(0, rel_path, )) + '?next=%s' % nxt


def url_addtag(request, rel_path):
    nxt = request.GET.get('next', request.get_full_path())
    return reverse('pygal-addtag', args=(rel_path, )) + '?next=%s' % nxt


def url_tagedit(request, tag_id):
    nxt = request.GET.get('next', request.get_full_path())
    return reverse('pygal-edittag', args=(tag_id, )) + '?next=%s' % nxt


def is_helpview(request):
    return request.META['PATH_INFO'].startswith(reverse('pygal-helpview', kwargs={'page': '_'})[:-1])


def is_infoview(request):
    return get_responsetype(request) == RESP_TYPE_INFOVIEW


def is_repeatview(request):
    return 'repeat' in request.GET


def is_favouriteview(request):
    return get_datatype(request) == DATA_TYPE_SEARCH and get_search_query(request) == 'favourite_of:%s' % request.user.username


def is_searchview(request):
    return not is_favouriteview(request) and get_datatype(request) == DATA_TYPE_SEARCH


def is_flat(request):
    return 'flat' in request.GET


def get_shuffle_id(request):
    return request.GET.get('shuffle')


def get_search_query(request):
    return request.GET.get('q')
