#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "include/mysql.h"


int main() {

   MYSQL *conn;
   MYSQL_RES *res;
   MYSQL_ROW vysledek;
   MYSQL_ROW vysledek2;

   char *server = "147.229.144.201";
   char *user = "rezny";
   char *password = "33gh44";
   char *database = "rezny";

   conn = mysql_init(NULL);

   if (!mysql_real_connect(conn, server,
         user, password, database, 0, NULL, 0)) {
      fprintf(stderr, "%s\n", mysql_error(conn));
      exit(1);
   }


    char typpaketu[2];
    char idsnimace[32];
    char data[10];
    char dotaz[128];
    char aktcas[11];
    char temp[4];

	int socketDescriptor;

	unsigned short int serverPort = 51236;

	unsigned int msgSize = 100; // maximalni delka dat
	struct sockaddr_in serverAddress, clientAddress;
	socklen_t clientAddressLength;
	char msg[msgSize];  // buffer pro prijata data
	socketDescriptor = socket(AF_INET, SOCK_DGRAM, 0);
	serverAddress.sin_family = AF_INET;
	serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1");
	serverAddress.sin_port = serverPort;

	if (bind(socketDescriptor, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) < 0) {
		printf("Nemohu navazat na socket! Adresa nebo port jsou jiz vyuzivany.");
		exit(1);
	}

	listen(socketDescriptor, 2); // moznost prijmout 2 zpravy najednou v queue
	printf("Nasloucham data na UDP portu %i\n", serverPort);



    char field[32];
    int n;
    int part=0;


        while(1) {
		clientAddressLength = sizeof(clientAddress);
		memset(msg, 0, msgSize);  // vynulovat buffer

		if (recvfrom(socketDescriptor, msg, msgSize, 0, (struct sockaddr *)&clientAddress, &clientAddressLength) < 0) {
		   printf("Nastala chyba pri prijmu dat!");
			exit(1);
		}

		//printf("Cas: %d: od %s:%d (%d): \n%s\n", time(NULL),inet_ntoa(clientAddress.sin_addr), serverAddress.sin_port, ntohs(clientAddress.sin_port), msg);	}
        printf("\n      Cas: %d\n   Prikaz: %s\n", time(NULL), msg);

        char *ptr=msg;
        part=0;
        while (sscanf(ptr,"%31[^;]%n",field,&n)==1)
         {
         part++;
         switch (part)
          {case 1:
             //strcpy(typpaketu,field);
             typpaketu[0]=field[0];
             typpaketu[1]='\0';
             break;
           case 2:
             strcpy(idsnimace,field);
             break;
           case 3:
             strcpy(data,field);
             break;
         }
         ptr+=n;
         if (*ptr!=';'){break;}
         ++ptr;
         }

         printf("typpaketu: %s\n",typpaketu);      // proc se typpaketu rovna typpaketu a data zaroven?? :D
         printf("idsnimace: %s\n",idsnimace);
         printf("     data: %s\n",data);

         sprintf(aktcas,"%d",time(NULL));

         if (typpaketu[0]=='1')  // PRIPOJENI ZARIZENI
         {
           strcpy(dotaz, "SELECT id FROM sensors WHERE mac LIKE '");
           strcat(dotaz, idsnimace);
           strcat(dotaz, "'");
           printf("%s \n",dotaz);
           mysql_query(conn, dotaz);
           fprintf(stderr, "%s\n", mysql_error(conn));
           res = mysql_use_result(conn);
           vysledek = mysql_fetch_row(res);

           if (vysledek == NULL)  // MAC NEZNAMA
             {
               strcpy(dotaz, "INSERT INTO sensors (`id`,`mac`,`active`,`lastseen`) VALUES (NULL,'");
               strcat(dotaz, idsnimace);
               strcat(dotaz, "','1','");
               strcat(dotaz, aktcas);
               strcat(dotaz, "')");
               printf("%s \n",dotaz);
               mysql_query(conn, dotaz);
               fprintf(stderr, "%s\n", mysql_error(conn));
             }
           else
             {
               strcpy(dotaz, "UPDATE sensors SET active = '1', lastseen = '");  // MAC ZNAMA
               strcat(dotaz, aktcas);
               strcat(dotaz, "' WHERE id='");
               strcat(dotaz, vysledek[0]);
               strcat(dotaz, "'");
               printf("%s \n",dotaz);
               while ((vysledek = mysql_fetch_row(res)) != NULL)   { }
               mysql_query(conn, dotaz);
               fprintf(stderr, "%s\n", mysql_error(conn));
             }



          } else if (typpaketu[0]=='2')    // ULOZENI DAT
         {
           strcpy(dotaz, "SELECT id FROM sensors WHERE mac LIKE '");
           strcat(dotaz, idsnimace);
           strcat(dotaz, "';");
           printf("%s \n",dotaz);
           mysql_query(conn, dotaz);
           fprintf(stderr, "%s\n", mysql_error(conn));
           res = mysql_use_result(conn);
           vysledek = mysql_fetch_row(res);
           strcpy(temp,vysledek[0]);

           strcpy(dotaz, "SELECT id FROM devices WHERE sensor='");
           strcat(dotaz, temp);
           strcat(dotaz, "';");
           printf("%s \n",dotaz);

           while ((vysledek = mysql_fetch_row(res)) != NULL)   { }
           mysql_query(conn, dotaz);
           fprintf(stderr, "%s\n", mysql_error(conn));
           res = mysql_use_result(conn);
           vysledek2 = mysql_fetch_row(res);

           if (vysledek2 == NULL)  // SNIMAC NEASOCIOVANY
             {
               strcpy(dotaz, "INSERT INTO temp (`id`,`sensor`,`data`,`time`) VALUES (NULL,'");
               strcat(dotaz, temp);
               strcat(dotaz, "','");
               strcat(dotaz, data);
               strcat(dotaz, "','");
               strcat(dotaz, aktcas);
               strcat(dotaz, "');");
               printf("%s \n",dotaz);
               while ((vysledek2 = mysql_fetch_row(res)) != NULL)   { }
               mysql_query(conn, dotaz);
               res = mysql_use_result(conn);
               fprintf(stderr, "%s\n", mysql_error(conn));
             }
           else
             {
               strcpy(dotaz, "INSERT INTO data (`id`,`device`,`data`,`time`) VALUES (NULL,'");  // SNIMAC ASOCIOVANY
               strcat(dotaz, vysledek2[0]);
               strcat(dotaz, "','");
               strcat(dotaz, data);
               strcat(dotaz, "','");
               strcat(dotaz, aktcas);
               strcat(dotaz, "');");
               printf("%s \n",dotaz);
               while ((vysledek2 = mysql_fetch_row(res)) != NULL)   { }
               mysql_query(conn, dotaz);
               fprintf(stderr, "%s\n", mysql_error(conn));
             }


          } else if (typpaketu[0]=='3')   // ODPOJENI ZARIZENI
         {
           strcpy(dotaz, "SELECT id FROM sensors WHERE mac LIKE '");
           strcat(dotaz, idsnimace);
           strcat(dotaz, "';");
           printf("%s \n",dotaz);
           mysql_query(conn, dotaz);
           fprintf(stderr, "%s\n", mysql_error(conn));
           res = mysql_use_result(conn);
           vysledek = mysql_fetch_row(res);


           strcpy(dotaz, "UPDATE sensors SET active = '0', lastseen = '");
           strcat(dotaz, aktcas);
           strcat(dotaz, "' WHERE id='");
           strcat(dotaz, vysledek[0]);
           strcat(dotaz, "';");
           printf("%s \n",dotaz);
           
           while ((vysledek = mysql_fetch_row(res)) != NULL)   { }
           mysql_query(conn, dotaz);
           res = mysql_use_result(conn);
           fprintf(stderr, "%s\n", mysql_error(conn));
          }
 
 mysql_free_result(res);
        }
    mysql_close(conn);
	return 0;
}
