# -*- coding: utf-8 -*-

# Copyright 2011-2016 Mir Calculate. http://www.calculate-linux.org
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import datetime
import threading
from cert_cmd import find_cert_id
# Time life certificate in days
DAY_CERT = 600


def serv_post_cert(self):
    """ transfer the client certificate """
    cur_thread = threading.currentThread()
    certificate = cur_thread.client_cert
    if certificate is None:
        return [-3]

    checked_id = find_cert_id(certificate, self.data_path, self.certbase)
    try:
        if int(checked_id) < 1:
            return [-2]
    except ValueError:
        return [-4]
    results = []
    with open(self.certbase) as fd:
        t = fd.read()
        # See each line
        for line in t.splitlines():
            # and each word in line
            words = line.split()
            # if in line present certificate id
            if len(words) > 3:
                if words[0] == checked_id:
                    results.append(checked_id)
                    date = datetime.datetime.strptime(
                        words[2] + ' ' + words[3], '%Y-%m-%d %H:%M:%S.%f')
                    d = datetime.datetime.now() - date
                    v = DAY_CERT - d.days  # How many days left certificate
                    if v < 0:
                        # Method deleted certificate
                        v = -2  # expiry date has passed
                    # For a long time, is not displayed to the client
                    elif v > 60:
                        v = -1
                    results.append(v)
                    return results
    return [-4]
