from .base import Api, Http400, Http423
from common.util.clients import CacheClient
from hashlib import sha256
import datetime
import logging


class ServerLock(Api):
    http_method_names = ['get']

    @staticmethod
    def get(request, _):
        address = request.GET.get('address')
        action = request.GET.get('action')
        duration = request.GET.get('duration', 0)
        jobno = request.GET.get('jobno', 0)
        cache = CacheClient()

        if not action:
            raise Http400('Param ACTION not specified')
        if not address:
            raise Http400('Param ADDRESS not specified')

        dt_now = int(datetime.datetime.now().strftime('%s'))
        duration = int(float(duration))
        until = dt_now + duration
        data = None
        cache_key = 'serverlock_{}'.format(sha256(address.encode('utf-8')).hexdigest())

        try:
            data = cache.get(cache_key)
        except Exception:
            logging.info('Failed to get data from cache', exc_info=True)
        if not data:
            data = '0__0'
        [stored_jobno, stored_until] = data.split('__')
        stored_until = int(stored_until)
        stored_duration = stored_until - dt_now

        if action == 'check':
            if stored_until >= dt_now:
                return [{
                    'status': 'locked',
                    'jobno': stored_jobno,
                    'duration': stored_duration
                }]
            else:
                return [{
                    'status': 'available',
                    'jobno': None,
                    'duration': None
                }]
        elif action == 'lock':
            if not duration:
                raise Http400('Param DURATION not specified')
            if not jobno:
                raise Http400('Param JOBNO not specified')
            if stored_until >= dt_now:
                raise Http423('Already locked in job {}'.format(stored_jobno))
            cache.set(cache_key, '{}__{}'.format(str(jobno), str(until)))
            return [{'success': True}]
        elif action == 'unlock':
            cache.delete(cache_key)
            if stored_until >= dt_now:
                return [{'success': True}]
            else:
                return [{'success': False}]
        else:
            raise Http400('Unknown ACTION {}'.format(action))
