from cStringIO import StringIO
import subprocess
import xml.etree.ElementTree as ET

from django.shortcuts import render
from django.conf import settings

from askbot.conf import settings as askbot_settings
from askbot.models.files import ContributedFile
from askbot.models.post import Post


def files_list(request):
    files = list(ContributedFile.objects.exclude(kind__in=(0, 1)))
    data = {
        'app_name': askbot_settings.APP_SHORT_NAME,
        'formdefs': [x for x in files if x.kind == 2],
        'workflows': [x for x in files if x.kind == 3],
        'themes': [x for x in files if x.kind == 4],
    }
    return render(request, 'files_list.html', data)


def file_info(request, file_id):
    contributed_file = ContributedFile.objects.get(id=file_id)
    if contributed_file.kind == 2:
        return file_info_formdef(request, contributed_file)
    if contributed_file.kind == 3:
        template_name = 'file_info_workflow.html'
    elif contributed_file.kind == 4:
        template_name = 'file_info_theme.html'
    else:
        template_name = 'file_info.html'
    data = {
        'app_name': askbot_settings.APP_SHORT_NAME,
        'file': contributed_file,
    }
    return render(request, template_name, data)


def file_info_formdef(request, contributed_file):
    source_post = Post.objects.filter(attached_file=contributed_file)[0]
    data = {
        'app_name': askbot_settings.APP_SHORT_NAME,
        'file': contributed_file,
        'source_post': source_post,
        'source_post_url': source_post.get_absolute_url().encode('ascii'),
    }
    cmd = settings.WCS_PREVIEW_CMD[:]
    cmd.append(contributed_file.data.path)
    data['preview'] = unicode(
            subprocess.check_output(cmd, stderr=subprocess.STDOUT), 'utf-8')
    return render(request, 'file_info_formdef.html', data)
