import logging
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.utils.translation import ugettext as _

from settings.models import *
from settings.tools import get_settings_value

class Command(BaseCommand):
    help = 'Device information polling service.'

    logger = logging.getLogger(__name__)

    ignore_polling_intervals = False

    def add_arguments(self, parser):
        parser.add_argument(
            '--gmail', '-g',
            action='store_true',
            dest='gmail',
            default=False,
            help='Send test with Gmail.')

        parser.add_argument(
            '--mailgun', '-m',
            action='store_true',
            dest='mailgun',
            default=False,
            help='Send test with Mailgun.')

        parser.add_argument(
            '--test', '-t',
            action='store_true',
            dest='test',
            default=False,
            help='Just some tests...')

    def handle(self, *args, **options):
        """
        Parse the command line arguments or print help if none are provided.
        """
        if options['gmail']:
            self.send_test_gmail()
        elif options['mailgun']:
            self.send_test_mailgun()
        elif options['test']:
            self.just_test()
        else:
            self.send_test_gmail()
            self.send_test_mailgun()

    def just_test(self):
        value = get_settings_value('POLLER_PING_INTERVAL')
        self.logger.debug('IntValue: {}'.format(value))

        value = get_settings_value('DATETIME_FORMAT')
        self.logger.debug('StrValue: {}'.format(value))

    def send_test_gmail(self):
        """
        Ping all SNMP devices with their selected ping mode (ICMP or TCP) and
        update the status of the devices.
        """

        # me == my email address
        # you == recipient's email address
        me = "dofiloop@gmail.com"
        you = "zarlacming@gmail.com"

        try:

            # Create message container - the correct MIME type is multipart/alternative.
            msg = MIMEMultipart('alternative')
            msg['Subject'] = "Link"
            msg['From'] = 'DofiLoop Sentinel'
            msg['To'] = you

            # Create the body of the message (a plain-text and an HTML version).
            text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttps://www.python.org"
            html = """\
            <html>
              <head></head>
              <body>
                <p>Hi!<br>
                   How are you?<br>
                   Here is the <a href="https://www.python.org">link</a> you wanted.
                </p>
              </body>
            </html>
            """

            # Record the MIME types of both parts - text/plain and text/html.
            part1 = MIMEText(text, 'plain')
            part2 = MIMEText(html, 'html')

            # Attach parts into message container.
            # According to RFC 2046, the last part of a multipart message, in this case
            # the HTML message, is best and preferred.
            msg.attach(part1)
            msg.attach(part2)

            server = smtplib.SMTP('smtp.gmail.com', 587)
            server.starttls()
            server.login(me, "Jag.ar.en.liten.kanin")
            text = msg.as_string()
            server.sendmail(me, you, text)
            server.quit()
        except smtplib.SMTPAuthenticationError as e:
            self.logger.error('Gmail send failed. Authentication Error for "{}"'.format(me))
        except Exception as e:
            self.logger.exception(e)

    def send_test_mailgun(self):
        """
        Ping all SNMP devices with their selected ping mode (ICMP or TCP) and
        update the status of the devices.
        """

        # me == my email address
        # you == recipient's email address
        me = "sentinel@dofiloop.com"
        you = "zarlacming@gmail.com"

        try:

            # Create message container - the correct MIME type is multipart/alternative.
            msg = MIMEMultipart('alternative')
            msg['Subject'] = "Link"
            msg['From'] = 'DofiLoop Sentinel <sentinel@dofiloop.com>'
            msg['To'] = you

            # Create the body of the message (a plain-text and an HTML version).
            text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttps://www.python.org"
            html = """\
            <html>
              <head></head>
              <body>
                <p>Hi!<br>
                   How are you?<br>
                   Here is the <a href="https://www.python.org">link</a> you wanted.
                </p>
              </body>
            </html>
            """

            # Record the MIME types of both parts - text/plain and text/html.
            part1 = MIMEText(text, 'plain')
            part2 = MIMEText(html, 'html')

            # Attach parts into message container.
            # According to RFC 2046, the last part of a multipart message, in this case
            # the HTML message, is best and preferred.
            msg.attach(part1)
            msg.attach(part2)

            server = smtplib.SMTP('smtp.mailgun.org', 587)
            server.starttls()
            server.login(me, "Jag.ar.en.liten.kanin")
            text = msg.as_string()
            server.sendmail(me, you, text)
            server.quit()
        except smtplib.SMTPAuthenticationError as e:
            self.logger.error(
                'Mailgun send failed. Authentication Error for "{}"'.format(me))
        except Exception as e:
            self.logger.exception(e)