import buttons
led_state = "OFF"

def buttons_color(led_state):
    if led_state == 'Blinking':
        return buttons.blink_led
    elif led_state == 'Alternating':
        return buttons.alt_led
    else:
        return buttons.normal

def web_page():
    html = """<html>

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css"
     integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
    <style>
        html {
            font-family: Arial;
            display: inline-block;
            margin: 0px auto;
            text-align: center;
        }
        
        body {
            background: #FFFFFF
        }
        
        .btn {
          background-color: #7F7F7F;
          border-radius: 8px;
          border-style: none;
          box-sizing: border-box;
          color: #FFFFFF;
          cursor: pointer;
          flex-shrink: 0;
          font-size: 16px;
          font-weight: 500;
          height: 4rem;
          padding: 0 1.6rem;
          text-align: center;
          transition: all .5s;
          user-select: none;
          -webkit-user-select: none;
          touch-action: manipulation;
        }
        
        .btnClick {
              background-color: #4169e1;
              border-radius: 8px;
              border-style: none;
              box-sizing: border-box;
              color: #FFFFFF;
              cursor: pointer;
              flex-shrink: 0;
              font-size: 16px;
              font-weight: 500;
              height: 4rem;
              padding: 0 1.6rem;
              text-align: center;
              transition: all .5s;
              user-select: none;
              -webkit-user-select: none;
              touch-action: manipulation;
        }

        
    </style>
</head>

<body>
    <h2>ESP32 MicroPython Web Server</h2>
    <p>LED Status: <strong>""" + led_state + """</strong></p>

    """ + buttons_color(led_state) + """
    
</body>

</html>"""
    return html


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)

from machine import Timer
from time import sleep

timer = Timer(0)


def blink(t):
        blue_led.value(not blue_led.value())
        red_led.value(not red_led.value())

def alt(t):
        red_led.off()
        blue_led.on()
        sleep(1)
        red_led.on()
        blue_led.off()
        sleep(1)

def off():
    if not timer.deinit():
        blue_led.off()
        red_led.off()
    else:
        timer.deinit()

while True:
    try:
        if gc.mem_free() < 102000:
            gc.collect()
        conn, addr = s.accept()
        conn.settimeout(3.0)
        print('Received HTTP GET connection request from %s' % str(addr))
        request = conn.recv(1024)
        conn.settimeout(None)
        request = str(request)
        print('GET Rquest Content = %s' % request)
        blink_led = request.find('/?blink_led')
        alt_led = request.find('/?alt_led')
        turn_off = request.find('/?turn_off')
        if blink_led == 6:
            print('Blinking...')
            led_state = "Blinking"
            off()
            timer.init(mode=Timer.PERIODIC, period=1000, callback=blink)
        elif alt_led == 6:
            print('Alternating...')
            led_state = "Alternating"
            off()
            timer.init(mode=Timer.PERIODIC, period=1000, callback=alt)
        elif turn_off == 6:
            print('Turning off...')
            led_state = "OFF"
            off()
        else:
            if led_state == "Blinking":
                off()
                timer.init(mode=Timer.PERIODIC, period=1000, callback=blink)
            elif led_state == "Alternating":
                off()
                timer.init(mode=Timer.PERIODIC, period=1000, callback=alt)
            elif led_state == "OFF":
                off()
    
        response = web_page()
        conn.send('HTTP/1.1 200 OK\n')
        conn.send('Content-Type: text/html\n')
        conn.send('Connection: close\n\n')
        conn.sendall(response)
        conn.close()
    except OSError as e:
        print(e)
        conn.close()
        print('Connection closed')