#!/usr/bin/env python
#-*- coding: utf-8 -*-
#create:2015-05-12 by mao_kxu@massclouds.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 mplatform.utils.ssh.ssh import ssh2
from mplatform.website.settings import FILE_ROOT
import logging
from mplatform.utils.db import dbbase
import time
from django.db import connection,transaction
from mplatform.utils.commondef import get_all_hosts
import os
import json

#import logging
logger = logging.getLogger(__name__)


@login_required
#@PermissionVerify()
def Listinfo(request):
    logger.debug('进入函数Listinfo request.method=%s',request.method)
    if request.method == "POST":
        #远程执行命令
        cmd = []#你要执行的命令列表
        ids = request.POST.get('ids')
        logger.debug('ids=%s',ids)
        ip = request.POST['ip']
        logger.debug('ip=%s',ip)
        username = request.POST['username']
        logger.debug('username=%s',username)
        password = request.POST['password']
        logger.debug('password=%s',password)
        db = dbbase.database()
        select_sql = "select command from debug_command where id in (%s)" % (ids)
        logger.debug('select_sql=%s',select_sql)
        debugcommandlist = db.select_fetchall(select_sql)
        for debugcommand in debugcommandlist:
	    #replace转义特殊字符
            echo_command = (('echo %s:'% debugcommand['command']).replace('|','\|')).replace('`','\`')
            cmd.append(echo_command)
            cmd.append('echo ""')
            cmd.append(debugcommand['command'])
            cmd.append('echo "\n===================================================================================================\n"')
        
        #a=threading.Thread(target=ssh2,args=(ip,username,password,cmd))
        #a.start()
        logger.debug('COMMAND=%s',cmd)
        result = ssh2(ip,username,password,cmd)
        if result == 'CONNECT_ERROR' or result.startswith('COMMAND_ERROR:'):
            return HttpResponse(result)
        #开始下载
        #fp = open(FILE_ROOT+'comand.txt','w')
        #fp.write(result)
        #response = HttpResponse(readFile(file_name))

        response = HttpResponse(content_type='text/plain')
        response['Content-Disposition'] = 'attachment; filename=command.txt'
        response.write(result)
        response.flush()
        return response
    else:
        db = dbbase.database()
        list = db.select_fetchall("select id,command,memo from debug_command")
    #print isolist
    kwvars = {
        'lPage':list,
        'request':request,
        'hosts':get_all_hosts()
    }
    logger.debug('退出函数Listinfo')
    return render_to_response('DebugManage/infocollection.list.html',kwvars,RequestContext(request))

@login_required
def forEditCommand(request,id):
    sql = "select id,command,memo from debug_command where id=%s" % id
    db = dbbase.database()
    info = db.select_fetchone(sql)
    kwvars = {'request':request,'info':info}
    return render_to_response('DebugManage/command.edit.html',kwvars,RequestContext(request))

@login_required
def editCommand(request):
    cmd_id = request.POST.get('cmd_id')
    command = request.POST.get('command')
    memo = request.POST.get('memo')
    sql = "update debug_command set command='%s',memo='%s' where id=%s" % (command,memo,cmd_id)
    db = dbbase.database()
    db.execute(sql)
    return HttpResponseRedirect(reverse('listinfocollectonurl'))

@login_required
def Editinfo(request):
    #iPermission = PermissionList.objects.get(id=ID)

    #if request.method == "POST":
     #   form = PermissionListForm(request.POST,instance=iPermission)
      #  if form.is_valid():
       #     form.save()
        #    return HttpResponseRedirect(reverse('listpermissionurl'))
    #else:
     #   form = PermissionListForm(instance=iPermission)

    kwvars = {
       # 'ID':ID,
       # 'form':form,
       # 'request':request,
    }

    return render_to_response('BasicManage/date.edit.html',kwvars,RequestContext(request))

#django.reqInMemoryUploadedFile
@login_required
def AddCommand(request):
    commanddict = {'id':'','id_errors':'','command':'','command_errors':'','memo':'','memo_errors':''}
    errors_flag = 0
    if request.method=='POST':
           #dir_name =
        commanddict['command'] = request.POST["command"]
        commanddict['memo'] = request.POST["memo"]
        cursor = connection.cursor()
        cursor.execute("select COALESCE(max(id),0)+1 as new_id from debug_command")
        id = cursor.fetchone()[0]
        cursor.execute("INSERT INTO debug_command(id, command, memo) values (%s, %s, %s)", [id, commanddict['command'], commanddict['memo']])
        transaction.commit()#commit_unless_managed()
        connection.commit()
        if errors_flag == 0 :
          return HttpResponseRedirect(reverse('listinfocollectonurl'))
    else:
        pass

    kwvars = {
        'commanddict':commanddict,
        'request':request,
    }

    return render_to_response('DebugManage/command.add.html',kwvars,RequestContext(request))

@login_required
def DeleteCommand(request):
    db = dbbase.database()
    ids = request.POST['ids']
    print '******************************'
    print ids
    logger.debug('ids=%s',ids)
    delete_sql = "delete from debug_command where id in (%s)" % ids
    print 'delete_sql='+delete_sql
    db.execute(delete_sql)
    list = db.select_fetchall("select id,command,memo from debug_command")
    return HttpResponse(json.dumps(list), content_type='application/json')
