#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <getopt.h>

#include "services_supported.h" //supported url shortening services
#include "shorturl.h" //shorturl() function

void kiel_uzi(short exitcode) //prints help message
{
    fprintf(stderr,
	"shorturl v0.8\n"
	"Usage: shorturl [-s <service's name>] [-u <long url>] \n"
	" -s - specify the shortening service\n"
	" -u - long url\n"
  "\nSupported services: clck and tinyurl.\n"
	"\nExample: shorturl -s clck.ru -u google.net\n");
}

int main(int argc, char *argv[])
{
    char service_name[APIURLSIZE] = DEFAULT;
		int opt; //will be needed for getopt()
    bool long_url_provided = false; //might be boolean

    if(argc == 1) kiel_uzi(1);

    while ( ( opt = getopt(argc, argv, "hs:u:") ) != -1)
		{
			switch (opt)
			{
				case 'h':
					kiel_uzi(1);
					return 0;
				case 's':
					memset(service_name, '\0', sizeof(service_name));
          if (strcmp(optarg, "clck") == 0) strcpy(service_name, CLCK_RU);
          else if (strcmp(optarg, "tinyurl") == 0) strcpy(service_name, TINYURL_COM);
          else {
						fprintf(stderr, "shorturl: incorrect service\n");
						exit(EXIT_FAILURE);
					}
          break;
				case 'u':
          long_url_provided = true;
          shorturl(optarg, service_name);
					break;
        default: kiel_uzi(1); return 0;
		}
	}

	if (long_url_provided == false)
	{
		unsigned bufsize = 3;
		char *long_url = malloc(bufsize * sizeof(char));
		int c;
		unsigned poz = 0;
		
		while (1){
			c = getchar();
			
			if (c == EOF || c == '\n') {
				long_url[poz] = '\0';
				shorturl(long_url, service_name);
				exit(EXIT_SUCCESS);
			}
			else
				long_url[poz] = c;
			
			poz++;
			
			if (poz > (bufsize - 2)){
				bufsize += 32;
				long_url = realloc(long_url, bufsize);
				if (!long_url) exit(EXIT_FAILURE);
			}
		}
	}

	return 0;
}
