#include "viewtube_controller_trains.h"
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

#define PORT 1989
#define SA struct sockaddr

void request_train_bytes_from_mta_server(char*, char);

void fetch_trains(viewtube_line_t *line, char line_number) {
   
    char recv_buf[4096]; // 4096 bytes should be enough. Typically we send 16-24 trains, so <200 bytes. 
    request_train_bytes_from_mta_server(recv_buf, line_number);
    
    char* recv_ptr = &recv_buf[0];
    short num_trains = (recv_ptr[0] << 8) + recv_ptr[1];
    recv_ptr += 2;
    printf("Received %d trains\n", num_trains);
    
    line->trains = malloc(num_trains * sizeof(viewtube_train_t));
    line->number_of_trains = num_trains;
    for (int i = 0; i < num_trains; i++) {        
        line->trains[i].previous_station = (recv_ptr[0] << 8) + recv_ptr[1];
        line->trains[i].next_station = (recv_ptr[2] << 8) + recv_ptr[3];
        line->trains[i].direction = recv_ptr[4];
        line->trains[i].distance_to_next_station = (recv_ptr[5] << 8) + recv_ptr[6];
        
        recv_ptr += 7;
    }

}

void free_trains(viewtube_line_t *line) {
    free(line->trains);
    line->number_of_trains = 0;
}

void request_train_bytes_from_mta_server(char* recv_buf, char line_number) {
    int sockfd, connfd;
    struct sockaddr_in servaddr, cli;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1) {
        printf("socket creation failed...\n");
        return;
    }
    bzero(&servaddr, sizeof(servaddr));
   
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    servaddr.sin_port = htons(PORT);
   
    if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0) {
        printf("connection with the server failed...\n");
        return;
    }

    char buf[80];
    bzero(buf, sizeof(buf));
    printf("Requesting route %c\n", line_number);
    buf[0] = line_number;
    buf[1] = '\n';
    write(sockfd, buf, sizeof(buf));
    bzero(buf, sizeof(buf));
    read(sockfd, recv_buf, 4096);

    close(sockfd);
}

// For debugging train output
void print_trains(viewtube_line_t *line) {
    for (int i = 0; i < line->number_of_trains; i++) {
        viewtube_train_t train = line->trains[i];
        printf("TRAIN: next_station=%d, previous_station=%d, direction=%c," 
            "distance_to_next_station=%f\n", train.next_station, train.previous_station,
            train.direction, train.distance_to_next_station);
    }
}

/*
int main() {
    // For Testing
    viewtube_line_t line = { NULL, 0, NULL, 0 };
    fetch_trains(&line, '6');
    print_trains(&line);
    free_trains(&line);
}
*/