#include <M5Unified.h>
#include <WiFi.h>
#include <HTTPClient.h> // ステータスコードの定義もここにある

const char* ssid = "ics-ap";
const char* password = "jikkenics";

WiFiServer server(80);

void setup() {
  auto cfg = M5.config();
  cfg.serial_baudrate = 115200;
  M5.begin(cfg);
  M5.Display.setRotation(3); //横向き
  M5.Display.setFont(&fonts::lgfxJapanGothic_16);
  M5.Display.println("webserver01");
  M5.Display.setTextScroll(true);

  WiFi.begin(ssid, password); // 接続開始
  while (WiFi.status() != WL_CONNECTED) { // 接続中...
    M5.Display.print(".");
    M5.delay(500);
  }
  // 接続完了！！
  M5.Display.fillScreen(GREEN);
  M5.Display.setCursor(0, 30, 4);//x,y,fonttype
  M5.Display.setTextColor(BLACK, GREEN);
  M5.Display.print("  Wifi Connected!\n");
  String gotip = WiFi.localIP().toString(); // m5デバイスのIPアドレス
  M5.Display.println(gotip);
  M5.Display.println("open Web via HTTP");

  server.begin(); // Webサーバを開始
}

void loop() {
  M5.update();
  WiFiClient client = server.available();
  if (client) {
    String req = "" ;
    String tmp = "" , meth = "" ;
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        req += c;
        if (c == '\n') {                    // if the byte is a newline character
          if (tmp.length() == 0) {  // end of request, break while loop
            break;
          } else { //まだ継続
            if (tmp.startsWith("GET ") || tmp.startsWith("POST ") ) {
              meth = tmp;
            }
            tmp = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          tmp += c;      // add it to the end of the currentLine
        }
      }
    } // end of while

    Serial.println(meth);
    if ( meth.startsWith("GET /") ) {
      client.println("HTTP/1.1 200 OK"); // header (with response code)
      client.println("Content-Type:text/plain");
      client.println(""); // HTTPでは、header と body の区切りは改行
      client.println(meth);
      client.println("-- request --");
      client.println(req);
    }

    if ( meth.startsWith("POST ") ) {
      String post = "";
      char buf[257];
      int n;
      while ((n = client.available()) > 0) {
        if (n < 256) {
          client.readBytes(buf, n) ;
          buf[n] = 0 ;
        } else {
          client.readBytes(buf, 256) ;
          buf[256] = 0 ;
        }
      }
      post += buf ;

      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type:text/plain");
      client.println(""); // HTTPでは、header と body の区切りは改行
      client.println(meth);
      client.println("-- request --");
      client.println(req);
      client.println("-- post data --");
      client.println(post);
    }
    // close the connection:
    client.stop();
    Serial.println(" --- Client Disconnected.");
  }
  M5.delay(20);
}