/* TCHVIEW.C - The Cat Helpfile Viewer (Win32 Final) */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <commdlg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "TCHELP.H"

#define ID_LIST 100
#define ID_TEXT 101
#define ID_CMB  102
#define IDM_OPEN 201
#define IDM_EXIT 202

HelpData* g_pData = NULL;
HWND hList, hText, hCmb;
int g_curLang = 0;
HINSTANCE g_hInst;

#define MAX_PATHS 20
char g_searchPaths[MAX_PATHS][MAX_PATH];
int g_pathCount = 0;

/* --- PFAD LOGIK --- */
void LoadPathFile() {
    char exePath[MAX_PATH], pathFile[MAX_PATH], line[MAX_PATH];
    FILE* f; char* p;

    g_pathCount = 0;
    GetCurrentDirectory(MAX_PATH, g_searchPaths[0]);
    g_pathCount++;

    GetModuleFileName(NULL, exePath, MAX_PATH);
    p = strrchr(exePath, '\\'); if(p) *p=0;
    wsprintf(pathFile, "%s\\Path", exePath);

    f = fopen(pathFile, "r");
    if (f) {
        while (fgets(line, MAX_PATH, f)) {
            line[strcspn(line, "\r\n")] = 0;
            if (strlen(line) > 0 && g_pathCount < MAX_PATHS) {
                strcpy(g_searchPaths[g_pathCount++], line);
            }
        }
        fclose(f);
    }
}

int ResolvePath(char* input, char* outPath) {
    int i, e;
    char testPath[MAX_PATH];
    char candidate[MAX_PATH];
    /* Unterstützung für beide Endungen */
    char* extensions[] = { "", ".tchelp", ".TCH", ".tch" };
    
    for(e=0; e<4; e++) {
        wsprintf(candidate, "%s%s", input, extensions[e]);
        
        /* 1. Direkt prüfen */
        if (GetFileAttributes(candidate) != 0xFFFFFFFF) {
            strcpy(outPath, candidate);
            return 1;
        }

        /* 2. In Pfaden suchen */
        for(i=0; i<g_pathCount; i++) {
            wsprintf(testPath, "%s\\%s", g_searchPaths[i], candidate);
            if (GetFileAttributes(testPath) != 0xFFFFFFFF) {
                strcpy(outPath, testPath);
                return 1;
            }
        }
    }
    return 0;
}

/* --- UI LOGIK --- */
void ResizeControls(HWND hwnd) {
    RECT rc;
    int listW = 200;
    GetClientRect(hwnd, &rc);
    MoveWindow(hCmb, 5, 5, listW, 300, TRUE);
    MoveWindow(hList, 5, 35, listW, rc.bottom - 40, TRUE);
    MoveWindow(hText, listW + 10, 5, rc.right - listW - 15, rc.bottom - 10, TRUE);
}

void RefreshUI() {
    int i;
    SendMessage(hList, LB_RESETCONTENT, 0, 0);
    if (g_pData && g_pData->lang_cnt > 0) {
        for(i=0; i<g_pData->lang[g_curLang].sec_cnt; i++) {
            SendMessage(hList, LB_ADDSTRING, 0, (LPARAM)g_pData->lang[g_curLang].sec[i].name);
        }
        SetWindowText(hText, g_pData->lang[g_curLang].desc);
    } else SetWindowText(hText, "");
}

void ShowSection(int index) {
    if (g_pData && index >= 0 && index < g_pData->lang[g_curLang].sec_cnt) {
        SetWindowText(hText, g_pData->lang[g_curLang].sec[index].text);
    }
}

void LoadAndShow(HWND hwnd, char* filename) {
    char fullPath[MAX_PATH];
    if (ResolvePath(filename, fullPath)) {
        if (!g_pData) g_pData = (HelpData*)malloc(sizeof(HelpData));
        if (TC_LoadXML(fullPath, g_pData)) {
            int idx;
            char title[512];
            /* NAME ANGEPASST */
            wsprintf(title, "The Cat Helpfile Viewer - %s", fullPath);
            SetWindowText(hwnd, title);

            SendMessage(hCmb, CB_RESETCONTENT, 0, 0);
            for(idx=0; idx<g_pData->lang_cnt; idx++) {
                SendMessage(hCmb, CB_ADDSTRING, 0, (LPARAM)g_pData->lang[idx].key);
            }
            g_curLang = 0;
            SendMessage(hCmb, CB_SETCURSEL, 0, 0);
            RefreshUI();
        } else MessageBox(hwnd, "Fehler beim Laden!", "Error", MB_OK|MB_ICONERROR);
    } else {
        char msg[300];
        wsprintf(msg, "Datei nicht gefunden:\n%s", filename);
        MessageBox(hwnd, msg, "Error", MB_OK|MB_ICONWARNING);
    }
}

void DoOpenFile(HWND hwnd) {
    OPENFILENAME ofn;
    char szFile[MAX_PATH];
    memset(&ofn, 0, sizeof(ofn));
    szFile[0] = 0;
    ofn.lStructSize = sizeof(ofn);
    ofn.hwndOwner = hwnd;
    ofn.lpstrFile = szFile;
    ofn.nMaxFile = sizeof(szFile);
    /* FILTER ANGEPASST: Zeigt The Cat Helpfile (.tchelp und .tch) */
    ofn.lpstrFilter = "The Cat Helpfile (*.tchelp;*.tch)\0*.tchelp;*.tch\0Alle Dateien (*.*)\0*.*\0";
    ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER;

    if (GetOpenFileName(&ofn)) {
        LoadAndShow(hwnd, ofn.lpstrFile);
    }
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
    int idx;
    switch(msg) {
        case WM_CREATE:
            {
                HFONT hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
                hCmb = CreateWindowEx(0, "COMBOBOX", "", WS_CHILD|WS_VISIBLE|CBS_DROPDOWNLIST|WS_VSCROLL, 0,0,0,0, hwnd, (HMENU)ID_CMB, g_hInst, NULL);
                SendMessage(hCmb, WM_SETFONT, (WPARAM)hFont, 0);
                hList = CreateWindowEx(WS_EX_CLIENTEDGE, "LISTBOX", "", WS_CHILD|WS_VISIBLE|WS_VSCROLL|LBS_NOTIFY, 0,0,0,0, hwnd, (HMENU)ID_LIST, g_hInst, NULL);
                SendMessage(hList, WM_SETFONT, (WPARAM)hFont, 0);
                hText = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "", WS_CHILD|WS_VISIBLE|WS_VSCROLL|ES_MULTILINE|ES_READONLY, 0,0,0,0, hwnd, (HMENU)ID_TEXT, g_hInst, NULL);
                SendMessage(hText, WM_SETFONT, (WPARAM)hFont, 0);
                SetWindowText(hText, "Bitte Datei oeffnen...");
                LoadPathFile();
            }
            return 0;
        case WM_SIZE: ResizeControls(hwnd); return 0;
        case WM_COMMAND:
            if (LOWORD(wParam) == IDM_OPEN) DoOpenFile(hwnd);
            else if (LOWORD(wParam) == IDM_EXIT) PostQuitMessage(0);
            else if (LOWORD(wParam) == ID_CMB && HIWORD(wParam) == CBN_SELCHANGE) {
                idx = SendMessage(hCmb, CB_GETCURSEL, 0, 0);
                if (idx != CB_ERR) { g_curLang = idx; RefreshUI(); }
            }
            else if (LOWORD(wParam) == ID_LIST && HIWORD(wParam) == LBN_SELCHANGE) {
                idx = SendMessage(hList, LB_GETCURSEL, 0, 0);
                if (idx != LB_ERR) ShowSection(idx);
            }
            return 0;
        case WM_DESTROY: if (g_pData) free(g_pData); PostQuitMessage(0); return 0;
    }
    return DefWindowProc(hwnd, msg, wParam, lParam);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrev, LPSTR cmd, int show) {
    WNDCLASSEX wc = {0}; MSG msg; HMENU hMenu; HWND hwnd;
    g_hInst = hInstance;
    wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW|CS_VREDRAW; wc.lpfnWndProc = WndProc;
    wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE+1);
    wc.lpszMenuName = NULL; wc.lpszClassName = "TCHViewClass";
    RegisterClassEx(&wc);

    hMenu = CreateMenu();
    { HMENU h = CreateMenu(); AppendMenu(h, MF_STRING, IDM_OPEN, "&Open..."); AppendMenu(h, MF_SEPARATOR, 0, NULL); AppendMenu(h, MF_STRING, IDM_EXIT, "E&xit"); AppendMenu(hMenu, MF_POPUP, (UINT)h, "&File"); }

    /* NAME ANGEPASST */
    hwnd = CreateWindowEx(WS_EX_APPWINDOW, "TCHViewClass", "The Cat Helpfile Viewer", 
        WS_OVERLAPPEDWINDOW|WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, NULL, hMenu, hInstance, NULL);

    ShowWindow(hwnd, show); UpdateWindow(hwnd);
    if (cmd && strlen(cmd) > 0) LoadAndShow(hwnd, cmd);
    while(GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); }
    return msg.wParam;
}