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

from django.db import models
from django import forms
from django.forms import ModelForm
from django.utils.translation import ugettext as _

class ContributedFile(models.Model):
    data = models.FileField(upload_to='files', null=True, max_length=250)
    kind = models.IntegerField(default=0)
        # enum values:
        #  0: not identified yet
        #  1: unknown
        #  2: formdef
        #  3: workflow
        #  4: theme
    title = models.CharField(max_length=255, null=True)

    class Meta:
        app_label = 'askbot'
        db_table = 'askbot_contributed_files'

    def get_kind_label_tag(self):
        return {
            2: _('form'),
            3: _('workflow'),
            4: _('theme'),
        }.get(self.kind)

    kind_label = property(get_kind_label_tag)

    def identify(self):
        if zipfile.is_zipfile(self.data.path):
            self.identify_maybe_theme(self.data.path)
            self.save()
            return
        try:
            document = ET.parse(self.data.path).getroot()
        except xml.etree.ElementTree.ParseError:
            self.kind = 0
            self.save()
            return
        if document.tag == 'formdef':
            self.kind = 2
            self.title = document.find('name').text
            self.save()
            return
        elif document.tag == 'workflow':
            self.kind = 3
            self.title = document.find('name').text
            self.save()
            return
        self.kind = 1
        self.save()

    def identify_maybe_theme(self, fd):
        with zipfile.ZipFile(fd) as z:
            filename_list = [x for x in z.namelist() if x[0] != '/' and x[-1] != '/']
            theme_name = filename_list[0].split('/')[0]
            if not ('%s/desc.xml' % theme_name) in filename_list:
                # Theme is missing a desc.xml file.
                self.kind = 1
                return
            desc_xml = z.read('%s/desc.xml' % theme_name)
            try:
                document = ET.fromstring(desc_xml)
            except xml.etree.ElementTree.ParseError:
                self.kind = 1
                return
            self.kind = 4
            self.title = document.find('label').text
