#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// структура компьютер
struct Computer {
    char model[25];
    char brand[25];
    int year;
    double price;
};

// запись компьютеров в бинарный файл
void writeComputersToFile(struct Computer computers[], int size, char* filename) {
    FILE* file = fopen(filename, "wb"); // открываем файл для записи в бинарном режиме
    if (file == NULL) {
        printf("Ошибка открытия файла.\n");
        return;
    }
    fwrite(computers, sizeof(struct Computer), size, file); // записываем компьютеры в файл
    fclose(file); // закрываем файл
}

// чтение компьютеров из бинарного файла
void readComputersFromFile(struct Computer computers[], int* size, char* filename) {
    FILE* file = fopen(filename, "rb"); // открываем файл для чтения в бинарном режиме
    if (file == NULL) {
        printf("Ошибка открытия файла.\n");
        return;
    }
    fseek(file, 0, SEEK_END); // перемещаем указатель в конец файла
    int fileSize = ftell(file); // определяем размер файла
    *size = fileSize / sizeof(struct Computer); // вычисляем количество компьютеров в файле
    rewind(file); // перемещаем указатель в начало файла
    fread(computers, sizeof(struct Computer), *size, file); // считываем компьютеры из файла
    fclose(file); // закрываем файл
}
// обновление данных в файле
void updateComputersInFile(struct Computer computers[], int size, char* filename) {
    writeComputersToFile(computers, size, filename);
    readComputersFromFile(computers, &size, filename);
}
// вывод компьютеров на экран
void printComputers(struct Computer computers[], int size) {
    // подробнее о выводе строк тут: stackoverflow.com/a/23777065
    printf("%-25s %-25s %-10s %-10s\n", "Model", "Brand", "Year", "Price");
    for (int i = 0; i < size; i++)
        printf("%-25s %-25s %-10d %-10.2lf\n", computers[i].model, computers[i].brand, computers[i].year, computers[i].price);
    printf("\n");
}

// удаление компьютера из массива
void deleteComputer(struct Computer computers[], int* size, int index) {
    for (int i = index; i < *size - 1; i++)
        computers[i] = computers[i + 1];
    (*size)--;
}

// поиск компьютера с минимальной стоимостью
int findMinPriceComputer(struct Computer computers[], int size) {
    int minIndex = 0;
    for (int i = 1; i < size; i++) 
        if (computers[i].price < computers[minIndex].price) 
        minIndex = i;
    
    return minIndex;
}

// поиск компьютера с максимальным годом выпуска
int findMaxYearComputer(struct Computer computers[], int size) {
    int maxIndex = 0;
    for (int i = 1; i < size; i++) 
        if (computers[i].year > computers[maxIndex].year) 
        maxIndex = i;
    
    return maxIndex;
}
// вставка нового компьютера в массив
void insertComputer(struct Computer computers[], int* size, struct Computer computer) {
    if (*size == 0) { // если массив пустой, то вставляем компьютер в начало
        computers[0] = computer;
        (*size)++;
    } else {
        int index = -1;
        for (int i = 0; i < *size; i++)
            if (computers[i].price == 1000) { // ищем компьютер со стоимостью 1000
                index = i;
                break;
            }
        if (index == -1) { // если такого компьютера нет, то вставляем новый компьютер в конец массива
            computers[*size] = computer;
            (*size)++;
        } else { // если нашли, то вставляем новый компьютер после него
            (*size)++;
            for (int i = *size - 1; i > index + 1; i--)
                computers[i] = computers[i - 1];
            computers[index + 1] = computer;
        }
    }
}

int main() {
    struct Computer computers[5] = {
        {"MacBook Pro", "Apple", 2021, 1999.99},
        {"Inspiron 15", "Dell", 2019, 799.99},
        {"ZenBook UX425", "Asus", 2020, 1199.99},
        {"ThinkPad X1", "Lenovo", 2018, 1499.99},
        {"Surface Laptop 3", "Microsoft", 2019, 1299.99}
    };
    int size = 5;
    char filename[] = "computers.dat";
    
    updateComputersInFile(computers, size, filename);
    printf("Изначальные компьютеры:\n");
    printComputers(computers, size);
    
    // task_1
    int minPriceIndex = findMinPriceComputer(computers, size);
    printf("Удаляем компьютер с минимальной стоимостью: %s\n", computers[minPriceIndex].model);
    deleteComputer(computers, &size, minPriceIndex);
    printComputers(computers, size);
    
    // task_2
    int maxYearIndex = findMaxYearComputer(computers, size);
    printf("Меняем местами компьютеры с минимальной стоимостью и максимальным годом выпуска (то есть самым новым): %s и %s\n", computers[minPriceIndex].model, computers[maxYearIndex].model);
    struct Computer temp = computers[minPriceIndex];
    computers[minPriceIndex] = computers[maxYearIndex];
    computers[maxYearIndex] = temp;
    updateComputersInFile(computers, size, filename);
    printComputers(computers, size);
    
    // task_3
    struct Computer newComputer;
    printf("Введите данные нового компьютера:\n");
    printf("Модель: ");
    scanf("%s", newComputer.model);
    printf("Марка: ");
    scanf("%s", newComputer.brand);
    printf("Год выпуска: ");
    scanf("%d", &newComputer.year);
    printf("Стоимость: ");
    scanf("%lf", &newComputer.price);
    
    insertComputer(computers, &size, newComputer);
    updateComputersInFile(computers, size, filename);
    printf("Обновленные компьютеры:\n");
    printComputers(computers, size);
    
    return 0;
}