import base64
import datetime
import glob
import io
import logging
import sys
from calendar import monthrange

import serial
from PIL import Image


def serial_ports():
    """ Lists serial port names

        :raises EnvironmentError:
            On unsupported or unknown platforms
        :returns:
            A list of the serial ports available on the system
    """
    if sys.platform.startswith('win'):
        ports = ['COM%s' % (i + 1) for i in range(256)]
    elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
        # this excludes your current terminal "/dev/tty"
        ports = glob.glob('/dev/tty[A-Za-z]*[0-9]*')
    elif sys.platform.startswith('darwin'):
        ports = glob.glob('/dev/tty.*')
    else:
        raise EnvironmentError('Unsupported platform')

    result = []
    for port in ports:
        try:
            s = serial.Serial(port)
            s.close()
            result.append(port)
        except (OSError, serial.SerialException):
            pass
    return result


def image_file_to_bytes(image64, size):
    image_file = io.BytesIO(base64.b64decode(image64))
    img = Image.open(image_file)
    img.thumbnail(size, Image.ANTIALIAS)
    bio = io.BytesIO()
    img.save(bio, format='PNG')
    imgbytes = bio.getvalue()
    return imgbytes


def calculateFutureDate(year, month, day, hour, minute, second, samples, interval):
    if None not in (year, month, day, hour, minute, second, samples, interval):
        seconds_in_future = (int(samples) - 1) * int(interval) if samples else samples
        logging.info("Trying to find the end date for " + str(seconds_in_future) + " seconds in the future")
        start_date = datetime.datetime(year=year, month=month, day=day, hour=hour, minute=minute, second=second)
        logging.info("Starting date is : " + str(start_date))
        end_date = start_date + datetime.timedelta(seconds=seconds_in_future)
        logging.info("Ending date is : " + str(end_date))
        return end_date.year, end_date.month, end_date.day, end_date.hour, end_date.minute, end_date.second
    else:
        logging.critical("The date was not set, got None")
        return year, month, day, hour, minute, second


def validateDate(year, month, day, hour, minute, second):
    if year < 1 or year > 9999:
        year = 1
    if month < 1 or month > 12:
        month = 1
    if day < 1 or day > monthrange(year, month)[1]:
        day = 1
    if hour < 0 or hour > 23:
        hour = 0
    if minute < 0 or minute > 59:
        minute = 0
    if second < 0 or second > 59:
        second = 0
    return year, month, day, hour, minute, second


def getMonthDays(year, month):
    if year is None:
        year = 1
    if month is None:
        month = 1
    return monthrange(year, month)[1]


# To convert your PNG into Base 64:
#   Go to https://www.base64-image.de/
#   Drag and drop your PNG image onto the webpage
#   Choose "Copy image"
#   Create a string variable name to hold your image
#   Paste data from webpage as a string
#   Delete the "header" stuff - up to the data portion (data:image/png;base64,)


green_button = "<KEY>" \
               "CA6jKpqjhQEgMLihA1l7veqeHYmrA692whLXxfo6e8czovTffmdmZR3BJclaJAhgDMAFgBMAwgA4AMbdtBDQFBQAagFUAKwDmCFhQJ2f23fyZnCokZ5UhAFOIbdwTBp/J6H8Jiu4AoTJILnoZuPtBBJwpvBQBdBl8txe8MAC+MaThn/" \
               "<KEY>" \
               "<KEY>" \
               "<KEY>" \
               "<KEY>" \
               "<KEY>" \
               "<KEY>" \
               "<KEY>" \
               "<KEY>RU5ErkJggg=="
red_button = "<KEY>" \
             "<KEY>" \
             "<KEY>" \
             "<KEY>" \
             "<KEY>" \
             "<KEY>" \
             "<KEY>" \
             "OaGqa9iyVTOau1abjlDRwKKWou25VKjVfPO+IZouyZX0shFjXE4nAouk34GGf2o8FcxqlFK7vV5VSnxdte7P9WscyE2BdSyTmhBBdU8bQp6RYMCdIKVFSbgL3252lRedCNsvSgZIS4iFCGBfNhGKHuQEoBVI2gUf830K2dlqlsgoeSCFM" \
             "<KEY>"
blue_button = "<KEY>" \
              "<KEY>" \
              "<KEY>" \
              "<KEY>" \
              "<KEY>" \
              "<KEY>" \
              "<KEY>" \
              "<KEY>" \
              "<KEY>" \
              "<KEY>"

import base64
import datetime
import glob
import io
import logging
import sys
from calendar import monthrange

import serial
from PIL import Image


def serial_ports():
    """ Lists serial port names

        :raises EnvironmentError:
            On unsupported or unknown platforms
        :returns:
            A list of the serial ports available on the system
    """
    if sys.platform.startswith('win'):
        ports = ['COM%s' % (i + 1) for i in range(256)]
    elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
        # this excludes your current terminal "/dev/tty"
        ports = glob.glob('/dev/tty[A-Za-z]*[0-9]*')
    elif sys.platform.startswith('darwin'):
        ports = glob.glob('/dev/tty.*')
    else:
        raise EnvironmentError('Unsupported platform')

    result = []
    for port in ports:
        try:
            s = serial.Serial(port)
            s.close()
            result.append(port)
        except (OSError, serial.SerialException):
            pass
    return result


def image_file_to_bytes(image64, size):
    image_file = io.BytesIO(base64.b64decode(image64))
    img = Image.open(image_file)
    img.thumbnail(size, Image.ANTIALIAS)
    bio = io.BytesIO()
    img.save(bio, format='PNG')
    imgbytes = bio.getvalue()
    return imgbytes


def calculateFutureDate(year, month, day, hour, minute, second, samples, interval):
    if None not in (year, month, day, hour, minute, second, samples, interval):
        seconds_in_future = (int(samples) - 1) * int(interval) if samples else samples
        logging.info("Trying to find the end date for " + str(seconds_in_future) + " seconds in the future")
        start_date = datetime.datetime(year=year, month=month, day=day, hour=hour, minute=minute, second=second)
        logging.info("Starting date is : " + str(start_date))
        end_date = start_date + datetime.timedelta(seconds=seconds_in_future)
        logging.info("Ending date is : " + str(end_date))
        return end_date.year, end_date.month, end_date.day, end_date.hour, end_date.minute, end_date.second
    else:
        logging.critical("The date was not set, got None")
        return year, month, day, hour, minute, second


def validateDate(year, month, day, hour, minute, second):
    if year < 1 or year > 9999:
        year = 1
    if month < 1 or month > 12:
        month = 1
    if day < 1 or day > monthrange(year, month)[1]:
        day = 1
    if hour < 0 or hour > 23:
        hour = 0
    if minute < 0 or minute > 59:
        minute = 0
    if second < 0 or second > 59:
        second = 0
    return year, month, day, hour, minute, second


def getMonthDays(year, month):
    if year is None:
        year = 1
    if month is None:
        month = 1
    return monthrange(year, month)[1]


# To convert your PNG into Base 64:
#   Go to https://www.base64-image.de/
#   Drag and drop your PNG image onto the webpage
#   Choose "Copy image"
#   Create a string variable name to hold your image
#   Paste data from webpage as a string
#   Delete the "header" stuff - up to the data portion (data:image/png;base64,)


green_button = "<KEY>" \
               "CA6jKpqjhQEgMLihA1l7veqeHYmrA692whLXxfo6e8czovTffmdmZR3BJclaJAhgDMAFgBMAwgA4AMbdtBDQFBQAagFUAKwDmCFhQJ2f23fyZnCokZ5UhAFOIbdwTBp/J6H8Jiu4AoTJILnoZuPtBBJwpvBQBdBl8txe8MAC+MaThn/" \
               "<KEY>" \
               "<KEY>" \
               "<KEY>" \
               "<KEY>" \
               "<KEY>" \
               "<KEY>" \
               "<KEY>" \
               "<KEY>RU5ErkJggg=="
red_button = "<KEY>" \
             "<KEY>" \
             "<KEY>" \
             "<KEY>" \
             "<KEY>" \
             "<KEY>" \
             "<KEY>" \
             "OaGqa9iyVTOau1abjlDRwKKWou25VKjVfPO+IZouyZX0shFjXE4nAouk34GGf2o8FcxqlFK7vV5VSnxdte7P9WscyE2BdSyTmhBBdU8bQp6RYMCdIKVFSbgL3252lRedCNsvSgZIS4iFCGBfNhGKHuQEoBVI2gUf830K2dlqlsgoeSCFM" \
             "<KEY>"
blue_button = "<KEY>" \
              "<KEY>" \
              "<KEY>" \
              "<KEY>" \
              "<KEY>" \
              "<KEY>" \
              "<KEY>" \
              "<KEY>" \
              "<KEY>" \
              "<KEY>"

Lists serial port names          :raises EnvironmentError:             On unsupported or unknown platforms         :returns:             A list of the serial ports available on the system # this excludes your current terminal "/dev/tty" # To convert your PNG into Base 64: #   Go to https://www.base64-image.de/ #   Drag and drop your PNG image onto the webpage #   Choose "Copy image" #   Create a string variable name to hold your image #   Paste data from webpage as a string #   Delete the "header" stuff - up to the data portion (data:image/png;base64,)