/*
    Voice Clock.
    For GNU/Linux 64 bit version.
    Version: 1 (C port).
    Written on C (https://en.wikipedia.org/wiki/C_(programming_language))
    Original Pascal version Copyright (C) 2025 Artyomov Alexander
    C port Copyright (C) 2026

    http://self-made-free.ru/
    aralni@mail.ru

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include <sys/time.h>

// Функция для получения дня недели (1=Пн, 7=Вс)
int weekday_ru(int year, int month, int day) {
    if (month < 3) {
        month += 12;
        year--;
    }
    int k = year % 100;
    int j = year / 100;
    int weekday = (day + 13*(month+1)/5 + k + k/4 + j/4 + 5*j) % 7;
    // Преобразуем: 0=Сб, 1=Вс, 2=Пн, 3=Вт, 4=Ср, 5=Чт, 6=Пт
    // Нам нужно: 1=Пн, 2=Вт, 3=Ср, 4=Чт, 5=Пт, 6=Сб, 7=Вс
    if (weekday == 0) return 6;      // Сб
    if (weekday == 1) return 7;      // Вс
    return weekday - 1;               // Пн-Пт
}

// Функция для выполнения команды и чтения вывода
char* exec_and_read(const char* cmd) {
    FILE* fp;
    char* result = malloc(256);
    if (!result) return NULL;
    result[0] = '\0';
    
    fp = popen(cmd, "r");
    if (fp != NULL) {
        if (fgets(result, 256, fp) != NULL) {
            // Убираем символ новой строки
            char* newline = strchr(result, '\n');
            if (newline) *newline = '\0';
        }
        pclose(fp);
    } else {
        free(result);
        return NULL;
    }
    return result;
}

int main(int argc, char* argv[]) {
    struct tm* tm_info;
    time_t rawtime;
    int hh, mm, ss, ms;  // ms не используется, но оставим для совместимости
    int yy, nn, dd;
    char c[16] = "na";
    char exedir[512];
    char cmd[1024];
    char* temperature_str;
    double IT = 0.0;
    char t[1024] = "";
    
    // Получаем директорию исполняемого файла
//    if (argc > 0) {
//        char* last_slash = strrchr(argv[0], '/');
//        if (last_slash) {
//            size_t len = last_slash - argv[0];
//            strncpy(exedir, argv[0], len);
//            exedir[len] = '\0';
//        } else {
//            strcpy(exedir, ".");
//        }
//    } else {
//        strcpy(exedir, ".");
//    }
    
    // Получаем температуру через termometerwttr
//    snprintf(cmd, sizeof(cmd), "%s/termometerwttr", exedir);
    snprintf(cmd, sizeof(cmd), "termometerwttr");
    temperature_str = exec_and_read(cmd);
    if (temperature_str && strlen(temperature_str) > 0) {
        strncpy(c, temperature_str, 15);
        c[15] = '\0';
        free(temperature_str);
    }
    
    // Если не удалось, пробуем termometeropenweathermap
    if (strcmp(c, "na") == 0) {
//        snprintf(cmd, sizeof(cmd), "%s/termometeropenweathermap", exedir);
        snprintf(cmd, sizeof(cmd), "termometeropenweathermap");
        temperature_str = exec_and_read(cmd);
        if (temperature_str && strlen(temperature_str) > 0) {
            strncpy(c, temperature_str, 15);
            c[15] = '\0';
            free(temperature_str);
        }
    }
    
    printf("%s\n", c);
    
    // Обрабатываем температуру
    if (strcmp(c, "na") != 0) {
        IT = atof(c);
        if (IT < 0) {
            strcat(t, " ~/.gorg64/voicedigits/t/minus.wav");
        }
        char temp_file[256];
        snprintf(temp_file, sizeof(temp_file), " ~/.gorg64/voicedigits/t/t%d.wav", abs((int)round(IT)));
        strcat(t, temp_file);
    }
    
    // Получаем текущее время и дату
    time(&rawtime);
    tm_info = localtime(&rawtime);
    
    hh = tm_info->tm_hour;
    mm = tm_info->tm_min;
    ss = tm_info->tm_sec;
    yy = tm_info->tm_year + 1900;
    nn = tm_info->tm_mon + 1;
    dd = tm_info->tm_mday;
    
    printf("The time is %d:%d:%d\n", hh, mm, ss);
    printf("The date is %d:%d:%d\n", yy, nn, dd);
    
    // Формируем команду mplayer
    char mplayer_cmd[2048];
    snprintf(mplayer_cmd, sizeof(mplayer_cmd),
             "mplayer ~/.gorg64/voicedigits/h/h%d.wav"
             " ~/.gorg64/voicedigits/m/m%d.wav"
             " ~/.gorg64/voicedigits/d/d%d.wav"
             " ~/.gorg64/voicedigits/n/n%d.wav"
             " ~/.gorg64/voicedigits/w/w%d.wav"
             " ~/.gorg64/voicedigits/y/y%d.wav%s",
             hh, mm, dd, nn, weekday_ru(yy, nn, dd), yy, t);
    
    system(mplayer_cmd);
    
    return 0;
}