# -*- coding: utf-8 -*-
"""
Created on Apr 19, 2016

@author: noob
"""
import json
import logging
import time
from datetime import datetime
# from django.db import connection
# from .util.clients import ClickhouseClient
from .util.clients import CacheClient
from django.http import HttpResponse, HttpResponseServerError
from django.contrib.auth.decorators import login_required
from .models import UISettings
import settings
from .models import ApiToken
from social_django.models import UserSocialAuth


def get_common(request, uid):
    common = {}
    # ===========================================================================
    # Notification bar in header
    # ===========================================================================
    cache = CacheClient()
    common['maintenance'] = cache.get('maintenance')
    try:
        do_not_notify = cache.get('do_not_notify_%s' % uid)
        if not do_not_notify:
            with open('/tmp/notification', 'r') as notifile:
                notification = json.loads(notifile.read().strip())
            now = time.mktime(datetime.now().timetuple())
            if int(notification['expire']) > now:
                common['notify_user'] = True
                common['notification_text'] = '%s @%s' % (notification['text'], notification['author']) if notification[
                    'text'] else ''
    except IOError:
        common['notify_user'] = False
        common['notification_text'] = ''
    except:
        logging.exception('')
        common['notify_user'] = False
        common['notification_text'] = ''
    # ===========================================================================
    try:
        user_extras = UserSocialAuth.objects.get(user_id=request.user.id)
        if user_extras.provider == 'github':
            common['avatar_link'] = 'https://avatars.githubusercontent.com/u/%s' % user_extras.uid
        elif user_extras.provider == 'yandex-oauth2':
            common['avatar_link'] = 'https://avatars.yandex.net/get-yapic/%s/islands-150' % user_extras.uid
    except UserSocialAuth.DoesNotExist:
        logging.error('User %s does not exist', request.user.id)
    except:
        logging.exception('')

    try:
        approved = ApiToken.objects.get(user=request.user).approved
    except ApiToken.DoesNotExist:
        approved = False
    except:
        logging.exception('')
        approved = False
    common['approved'] = approved
    common['production_env'] = settings.env_type
    common['CSP_SCRIPT_NONCE'] = settings.CSP_SCRIPT_NONCE
    common['CSP_STYLE_NONCE'] = settings.CSP_STYLE_NONCE
    return common


def ping(request):
    try:
        # ch_client = ClickhouseClient()
        # ch_client.select('select 1')
        # cursor = connection.cursor()
        # try:
        #     cursor.execute('select 1')
        # except Exception as exc:
        #     raise exc
        # finally:
        #     cursor.close()
        return HttpResponse('')
    except:
        logging.exception('')
        return HttpResponseServerError('')


@login_required
def ui_set(request):
    try:
        user = request.user
        param = request.GET.get('param', '')
        value = request.GET.get('value', '')
        ui_setting = UISettings.objects.get_or_create(user=user, param=param)[0]
        ui_setting.onoff = bool(value)
        ui_setting.save()
        return HttpResponse(json.dumps([{'success': 1}]), content_type='text/json')
    except:
        logging.exception('')
        return HttpResponse(json.dumps([{'success': 0}]), content_type='text/json')
