#include <stdio.h>
#include <winsock2.h>
#include <windows.h>
#include <string.h>
struct fileinfo
{
    char filepath[1024];
    char filename[512];
    char fileextention[8];
    char filecontent[2048];
    char *Pointer;
};


int main(int argc, char **argv)
{
    WSADATA wsa;
    SOCKET s;
    struct sockaddr_in server;
    struct sockaddr_in client;

    printf("Initialising Winsock2...\n");
    if(WSAStartup(MAKEWORD(2,2),&wsa) != 0)
    {
        printf("Failed. Error Code : %d\n", WSAGetLastError());
        return 1;
    }
    printf("Initialised.\n");

    if((s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
    {
        printf("Could not create socket : %d\n", WSAGetLastError());
        return 1;
    }
    printf("Socket created.\n");

    server.sin_addr.s_addr = inet_addr("192.168.0.6");
    server.sin_family = AF_INET;
    server.sin_port = htons(1234);

    // Binding
    if(bind(s, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR)
    {
        printf("Bind failed with error code : %d\n", WSAGetLastError());
        return 1;
    }else
    {
        printf("Binded\n");
    }

    printf("Listening incomming connections..\n");
    listen(s, 1);

    // Accept connections
    int c = sizeof(struct sockaddr_in);
    SOCKET s2 = accept(s, (struct sockaddr *)&client, &c);
    if(s2 != SOCKET_ERROR || INVALID_SOCKET)
    {
        printf("Connection accepted with %s on port %d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port));
    }else
    {
        printf("Connection failed with %s on port %d reason : %s\n",inet_ntoa(client.sin_addr), ntohs(client.sin_port), WSAGetLastError());
    }

    struct fileinfo SFileInformation;
    if(recv(s2, SFileInformation.filename, 512, 0) == SOCKET_ERROR)
    {
        printf("Error receiving file name: %d\n", WSAGetLastError());
        return 1;
    }else
    {
        printf("file name: %s\n", SFileInformation.filename);
    }
    if(recv(s2, SFileInformation.filecontent, 8112, 0) == SOCKET_ERROR)
    {
        printf("Error receiving file content: %d\n", WSAGetLastError());
        return 1;
    }

    // setting up file path
    strcpy(SFileInformation.filepath, SFileInformation.filename);
    printf("%s\n", SFileInformation.filepath);
    strcat(SFileInformation.filepath, SFileInformation.fileextention);
    printf("%s\n", SFileInformation.filepath);

    return 0;
    FILE *filehere = fopen(SFileInformation.filename, "wb+");
    if(filehere == NULL)
    {
        printf("Failed opening file");
    }
    if(fprintf(filehere, "%s", SFileInformation.filecontent) > 0)
    {
        printf("success !\n");
    }else
    {
        printf("Error writing in file");
    }

    fclose(filehere);
    closesocket(s2);
    closesocket(s);
    WSACleanup();

    return 0;
}