#!/usr/bin/env python
#-*- coding: utf-8 -*-
#update:2014-09-12 by liufeily@163.com

from django.core.urlresolvers import reverse
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response,RequestContext
from django.contrib.auth.decorators import login_required
from mplatform.website.common.CommonPaginator import SelfPaginator
from UserManage.views.permission import PermissionVerify
from django.contrib import auth
from django.contrib.auth import get_user_model
import logging
import ctypes 
import os
import tempfile
import datetime
from _codecs import encode
from django.core.servers.basehttp import FileWrapper

logger = logging.getLogger(__name__)
LIBMCOSLBASER = ctypes.CDLL('libmcoslbaser.so', use_errno=True)
LICENSE_DIR = '/mcos/license/'
TMPLICENSE_PATH = '/mcos/license/licenseTmp'
# LICENSE_PATH = '/mcos/license/license'

@login_required
def ListAuth(request):
    logger.debug('进入函数ListAuth')

    if not os.path.exists(LICENSE_DIR):
        os.makedirs(LICENSE_DIR)

#     license_info = ctypes.create_string_buffer(4096)
#     license_info_res = ''
#     if os.path.exists(LICENSE_PATH):
#         file_name2 = ctypes.create_string_buffer(4096) 
#         file_name2.value = LICENSE_PATH
#         buffer_len2 = ctypes.c_int(4096)
#         LIBMCOSLBASER.get_license_info(file_name2,license_info,buffer_len2)
#         license_info_res = pickLicenseinfo(license_info.value)

    hardinfo = ctypes.create_string_buffer(4096)
    buffer_len = ctypes.c_int(4096)
    LIBMCOSLBASER.get_host_info(hardinfo,buffer_len)

    data = {'hardinfo':hardinfo.value,'request':request}

    logger.debug('退出函数ListAuth')
    return render_to_response('AuthManage/auth.list.html', data, RequestContext(request))

@login_required
def ajaxGetLicenseInfo(request, product):
    license_info_res = ''
    try:
        license_info = ctypes.create_string_buffer(4096)
        license_path = LICENSE_DIR + product
        if os.path.exists(license_path): # 存在授权文件
            file_name2 = ctypes.create_string_buffer(4096) 
            file_name2.value = license_path
            buffer_len2 = ctypes.c_int(4096)
            LIBMCOSLBASER.get_license_info(file_name2,license_info,buffer_len2)
            license_info_res = pickLicenseinfo(license_info.value)
        else: # 没有授权文件，读取试用期文件
            probation_path = license_path + '_probation'
            if os.path.exists(probation_path):
                start_date_str = ''
                end_date_str = ''
                with open(probation_path,'r') as f:
                    start_date_str = f.read().replace('\n','')
                if start_date_str:
                    start_date = datetime.datetime.strptime(start_date_str, '%Y-%m-%d')
                    end_date = start_date + datetime.timedelta(89)
                    end_date_str = datetime.datetime.strftime(end_date, '%Y-%m-%d')
                    license_info_res = '试用期时间： %s 至 %s' % (start_date_str,end_date_str)
    except Exception as e:
        logger.error('Error in ajaxGetLicenseInfo: %s' % str(e))
    return HttpResponse(license_info_res)

def pickLicenseinfo(data):
    res = ''
    arr = data.split('\n')
    pickList_2 = ['producer','product','customer','startdata','enddata',
                'lictype','version_types','authtype','userno','cpuno',
                'vdino','idvno','Ukeysno','desktopno','onlineuserno']
    pickList_1 = ['producer','product','customer',
                'lictype','version_types','authtype','userno','cpuno',
                'vdino','idvno','Ukeysno','desktopno','onlineuserno']
    if 'lictype=2'in arr:
	pickList = pickList_1
    else:
	pickList = pickList_2	

    for line in arr:
        for keyword in pickList:
            if keyword in line:
                res += line + '\n'
                break
    return res
    

@login_required
def forupload(request,product):
    logger.debug('进入函数forupload')
    logger.debug('退出函数forupload')
    return render_to_response('AuthManage/auth.upload.html', {'request':request,'product':product}, RequestContext(request))


def upload(request):
    logger.debug('进入函数upload')
    file =  request.FILES['license_name']
    fd = open(TMPLICENSE_PATH, 'wb')
    for chunk in file.chunks():
        fd.write(chunk)
    fd.close()
    logger.debug('退出函数upload')
    return HttpResponse(getTmpLicenseInfo())


def getTmpLicenseInfo():
    logger.debug('进入函数getTmpLicenseInfo')
    file_name2 = ctypes.create_string_buffer(4096) 
    file_name2.value = TMPLICENSE_PATH
    license_info = ctypes.create_string_buffer(4096)
    buffer_len2 = ctypes.c_int(4096)
    result = LIBMCOSLBASER.get_license_info(file_name2,license_info,buffer_len2)
    logger.debug('退出函数getTmpLicenseInfo')
    return license_info.value


def downloadHardinfo(datainfo):
    logger.debug('进入函数downloadHardinfo')
    (fd, pipe) = tempfile.mkstemp()
    
    file_name2 = ctypes.create_string_buffer(4096)
    file_name2.value = pipe
    LIBMCOSLBASER.create_host_info_file(file_name2)

    f = open(pipe)
    os.remove(pipe)
    response = HttpResponse(FileWrapper(f), content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename=hardinfo'
    logger.debug('退出函数downloadHardinfo')
    return response


def licenseok(request,product):
    logger.debug('进入函数licenseok')
    license_path = LICENSE_DIR + product
    os.rename(TMPLICENSE_PATH, license_path)
    result  = os.system('systemctl restart massclouds-svmanager')
    logger.debug('******重启massclouds-svmanager结果 ' + str(result)  + '*********')
    logger.debug('退出函数licenseok')
    return HttpResponseRedirect('/auth/auth/list/?product=' + product)

