# Path: simone/models.py
# class ImapServer(models.Model):
#     user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
#     address = models.CharField(max_length=255,null=True)
#     port = models.IntegerField(default=143,null=True)
#     username = models.CharField(max_length=255,null=True)
#     passwd = models.CharField(max_length=255,null=True)
#     ssl = models.BooleanField(default=False)
#     def __str__(self):
#         if not self.address and not self.port and not self.username and not self.passwd:
#             return 'None'
#         if self.ssl:
#             return '%s@imaps://%s:%s' % (self.username, self.address, self.port)
#         return '%s@imap://%s:%s' % (self.username, self.address, self.port)
# 
# class SmtpServer(models.Model):
#     user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
#     address = models.CharField(max_length=255,null=True)
#     port = models.IntegerField(default=25,null=True)
#     username = models.CharField(max_length=255,null=True)
#     passwd = models.CharField("Password", max_length=255,null=True)
#     def __str__(self):
#         if not self.address and not self.port and not self.username and not self.passwd:
#             return 'None'
#         return '%s@smtp://%s:%s' % (self.username, self.address, self.port)
# 
# Path: simone/forms.py
# class ImapServerForm(forms.ModelForm):
#     class Meta:
#         model = ImapServer
#         exclude = ['user']
#         widgets = {
#             'passwd': forms.PasswordInput(),
#         }
# 
# class SmtpServerForm(forms.ModelForm):
#     class Meta:
#         model = SmtpServer
#         exclude = ['user']
#         widgets = {
#             'passwd': forms.PasswordInput(),
#         }


from django.views.generic import (
    CreateView,
    DeleteView,
    DetailView,
    UpdateView,
    ListView
)
from .models import (
	ImapServer,
	SmtpServer,
)
from .forms import (
    ImapServerForm,
    SmtpServerForm,
)
from pprint import pprint
from django.shortcuts import render, render_to_response, HttpResponse
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.urls import reverse
    from django.core.mail import send_mail, BadHeaderError#, EmailMultiAlternatives
import codecs
import email
import json
import smtplib
import sys
    import imapclient
    import imaplib
    import ssl
            ss.set_debuglevel(1)
            ss.starttls()
            ss.login(ssrv.username, ssrv.passwd)
            #ss.send_message(emsg) Python 3.2
            ss.sendmail(emsg.get('From'), emsg.get_all('To'), str(emsg))
            ss.quit()
            # FIXME handle html/multipart email
        except smtplib.SMTPAuthenticationError:
            return HttpResponse(json.dumps({'status':'ERROR', 'message': 'Invalid SMTP server settings'}))

        i = imapclient.IMAPClient(isrv.address, port=isrv.port, use_uid=False, ssl=isrv.ssl)
        i.login(isrv.username, isrv.passwd)

        i.select_folder('Sent')
        resp = i.append('Sent', str(emsg), [imapclient.SEEN])
        debug(resp)
        return HttpResponse(json.dumps({'status':'SUCCESS', 'message': 'Mail sent succesfully'})) # we can use short responses since we will only be submitting via ajax
    else:
        return HttpResponse(json.dumps({'status':'ERROR', 'message': 'Fill in all fields'+subject+message+mailfrom+mailto}))

@login_required
def config(request, action):
    """display form/change configuration settings, gets info from forms sent from browser

    :param request: request object from Django
    :param action: what action to do
    """
    if action == "newconfig" or action == "newIMAPform":
        """display new IMAP form"""
        # we already know they don't have anything in the database, just show them a blank form

# Path: simone/models.py
# class ImapServer(models.Model):
#     user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
#     address = models.CharField(max_length=255,null=True)
#     port = models.IntegerField(default=143,null=True)
#     username = models.CharField(max_length=255,null=True)
#     passwd = models.CharField(max_length=255,null=True)
#     ssl = models.BooleanField(default=False)
#     def __str__(self):
#         if not self.address and not self.port and not self.username and not self.passwd:
#             return 'None'
#         if self.ssl:
#             return '%s@imaps://%s:%s' % (self.username, self.address, self.port)
#         return '%s@imap://%s:%s' % (self.username, self.address, self.port)
# 
# class SmtpServer(models.Model):
#     user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
#     address = models.CharField(max_length=255,null=True)
#     port = models.IntegerField(default=25,null=True)
#     username = models.CharField(max_length=255,null=True)
#     passwd = models.CharField("Password", max_length=255,null=True)
#     def __str__(self):
#         if not self.address and not self.port and not self.username and not self.passwd:
#             return 'None'
#         return '%s@smtp://%s:%s' % (self.username, self.address, self.port)
# 
# Path: simone/forms.py
# class ImapServerForm(forms.ModelForm):
#     class Meta:
#         model = ImapServer
#         exclude = ['user']
#         widgets = {
#             'passwd': forms.PasswordInput(),
#         }
# 
# class SmtpServerForm(forms.ModelForm):
#     class Meta:
#         model = SmtpServer
#         exclude = ['user']
#         widgets = {
#             'passwd': forms.PasswordInput(),
#         }


# Path: simone/views.py
from django.views.generic import (
    CreateView,
    DeleteView,
    DetailView,
    UpdateView,
    ListView
)
from .models import (
	ImapServer,
	SmtpServer,
)
from .forms import (
    ImapServerForm,
    SmtpServerForm,
)
from pprint import pprint
from django.shortcuts import render, render_to_response, HttpResponse
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.urls import reverse
    from django.core.mail import send_mail, BadHeaderError#, EmailMultiAlternatives
import codecs
import email
import json
import smtplib
import sys
    import imapclient
    import imaplib
    import ssl

            ss.set_debuglevel(1)
            ss.starttls()
            ss.login(ssrv.username, ssrv.passwd)
            #ss.send_message(emsg) Python 3.2
            ss.sendmail(emsg.get('From'), emsg.get_all('To'), str(emsg))
            ss.quit()
            # FIXME handle html/multipart email
        except smtplib.SMTPAuthenticationError:
            return HttpResponse(json.dumps({'status':'ERROR', 'message': 'Invalid SMTP server settings'}))

        i = imapclient.IMAPClient(isrv.address, port=isrv.port, use_uid=False, ssl=isrv.ssl)
        i.login(isrv.username, isrv.passwd)

        i.select_folder('Sent')
        resp = i.append('Sent', str(emsg), [imapclient.SEEN])
        debug(resp)
        return HttpResponse(json.dumps({'status':'SUCCESS', 'message': 'Mail sent succesfully'})) # we can use short responses since we will only be submitting via ajax
    else:
        return HttpResponse(json.dumps({'status':'ERROR', 'message': 'Fill in all fields'+subject+message+mailfrom+mailto}))

@login_required
def config(request, action):
    """display form/change configuration settings, gets info from forms sent from browser

    :param request: request object from Django
    :param action: what action to do
    """
    if action == "newconfig" or action == "newIMAPform":
        """display new IMAP form"""
        # we already know they don't have anything in the database, just show them a blank form

        iform = ImapServerForm(initial={'address':'localhost', 'port':'143'})