// =============================================================== //
//                                                                 //
//   File      : NT_trackAliChanges.cxx                            //
//   Purpose   : Track alignment and sequences changes             //
//                                                                 //
//   Coded by Ralf Westram (coder@reallysoft.de) in June 2007      //
//   Institute of Microbiology (Technical University Munich)       //
//   http://www.arb-home.de/                                       //
//                                                                 //
// =============================================================== //

#include "NT_local.h"

#include <sel_boxes.hxx>
#include <aw_awar.hxx>
#include <aw_root.hxx>
#include <aw_msg.hxx>
#include <arb_progress.h>
#include <arb_strbuf.h>
#include <arbdbt.h>
#include <ctime>
#include <string>
#include <list>
#include <algorithm>

#define AWAR_TRACK_BASE "track/"
#define AWAR_TRACK_ALI  AWAR_TRACK_BASE "ali"
#define AWAR_TRACK_ID   AWAR_TRACK_BASE "initials" // [historical]

#define SEQ_HISTORY_FIELD "seq_history"

using std::string;
using std::list;

static GB_ERROR writeHistory(GBDATA *gb_species, const char *stamp, const char *entry) {
    char     *newContent = GBS_global_string_copy("%s %s", stamp, entry);
    GB_ERROR  error      = NULp;
    GBDATA   *gb_history = GB_entry(gb_species, SEQ_HISTORY_FIELD);

    if (!gb_history) error = GBT_write_string(gb_species, SEQ_HISTORY_FIELD, newContent);
    else {
        size_t oldSize = GB_read_string_count(gb_history);
        size_t newSize = strlen(newContent);

        GBS_strstruct content(oldSize+newSize+3);
        content.ncat(newContent, newSize);
        content.put('\n');
        content.ncat(GB_read_char_pntr(gb_history), oldSize);

        error = GB_write_string(gb_history, content.get_data());
    }

    free(newContent);

    return error;
}

static void trackAlignmentChanges(AW_window *aww) {
    GB_transaction ta(GLOBAL.gb_main);

    AW_root  *root           = aww->get_root();
    char     *ali            = root->awar(AWAR_TRACK_ALI)->read_string();
    char     *checksum_field = GBS_string_2_key(GBS_global_string("checksum_%s", ali));
    GB_ERROR  error          = NULp;
    char     *stamp;

    {
        const char *sessionID = root->awar(AWAR_TRACK_ID)->read_char_pntr();
        char        atime[256];
        time_t      t         = time(NULp);
        struct tm  *tms       = localtime(&t);

        strftime(atime, 255, "%Y/%m/%d %k:%M", tms);
        stamp = GBS_global_string_copy("%s %s", atime, sessionID);
    }

    arb_progress progress(GBS_global_string("Tracking changes in '%s'", ali), GBT_get_species_count(GLOBAL.gb_main));

    // add changekeys for generated fields:
    GB_warning_if(GBT_add_new_species_changekey(GLOBAL.gb_main, checksum_field, GB_STRING));
    GB_warning_if(GBT_add_new_species_changekey(GLOBAL.gb_main, SEQ_HISTORY_FIELD, GB_STRING));

    size_t newSpecies  = 0;
    size_t ali_changed = 0;
    size_t seq_changed = 0;
    size_t unchanged   = 0;

    for (GBDATA *gb_species = GBT_first_species(GLOBAL.gb_main);
         gb_species && !error;
         gb_species = GBT_next_species(gb_species))
    {
        GBDATA *gb_seq = GBT_find_sequence(gb_species, ali);
        if (gb_seq) {
            // has data in wanted alignment
            const char *seq          = GB_read_char_pntr(gb_seq);
            long        char_cs      = GBS_checksum(seq, 0, ".-");
            long        ali_cs       = GBS_checksum(seq, 0, "");
            char       *char_entry   = GBS_global_string_copy("%lx", char_cs);
            char       *ali_entry    = GBS_global_string_copy("%lx", ali_cs);
            const char *save_comment = NULp;

            GBDATA *gb_checksum = GB_entry(gb_species, checksum_field);
            if (!gb_checksum) {
                newSpecies++;
                gb_checksum             = GB_create(gb_species, checksum_field, GB_STRING);
                if (!gb_checksum) error = GB_await_error();
                else save_comment       = "new";
            }
            else {
                char *oldValue       = GB_read_string(gb_checksum);
                if (!oldValue) error = GB_await_error();
                else {
                    char *comma = strchr(oldValue, ',');
                    if (!comma) {
                        error = GBS_global_string("Invalid value '%s' in field '%s'", oldValue, checksum_field);
                    }
                    else {
                        comma[0] = 0;
                        if (strcmp(char_entry, oldValue) == 0) { // seq checksum is equal
                            if (strcmp(ali_entry, comma+1) == 0) { // ali checksum is equal
                                unchanged++;
                            }
                            else { // only alignment checksum changed
                                ali_changed++;
                                save_comment = "alignment changed";
                            }
                        }
                        else {
                            seq_changed++;
                            save_comment = "sequence changed";
                        }
                    }
                    free(oldValue);
                }
            }

            if (save_comment) {
                error             = GB_write_string(gb_checksum, GBS_global_string("%s,%s", char_entry, ali_entry));
                if (!error) error = writeHistory(gb_species, stamp, GBS_global_string("%s %s", ali, save_comment));
            }

            if (error) {
                error = GBS_global_string("%s (%s)", error, GBT_get_name_or_description(gb_species));
            }

            free(ali_entry);
            free(char_entry);
        }
        progress.inc_and_check_user_abort(error);
    }

    if (error) aw_message(error);
    else {
        struct ReportLine {
            string tag;
            size_t amount;
            ReportLine(string tag_, size_t amount_) : tag(tag_), amount(amount_) { }
        };

        list<ReportLine> reports;
        if (newSpecies)  reports.push_back(ReportLine("previously untracked",   newSpecies));
        if (unchanged)   reports.push_back(ReportLine("unchanged",              unchanged));
        if (ali_changed) reports.push_back(ReportLine("only alignment changed", ali_changed));
        if (seq_changed) reports.push_back(ReportLine("sequence changed",       seq_changed));

        if (!reports.empty()) {
            size_t tagMaxLen = 0;
            size_t amountMax  = 0;
            for (list<ReportLine>::const_iterator r = reports.begin(); r != reports.end(); ++r) {
                tagMaxLen = std::max(tagMaxLen, r->tag.length());
                amountMax = std::max(amountMax, r->amount);
            }

            size_t amountMaxLen = std::to_string(amountMax).length();
            GBS_strstruct msg;
            for (list<ReportLine>::const_iterator r = reports.begin(); r != reports.end(); ++r) {
                msg.catPadded(GBS_global_string("%s:", r->tag.c_str()), tagMaxLen+2);
                msg.nprintf(amountMaxLen, "%*zu", int(amountMaxLen), r->amount);
                msg.cat(" species\n");
            }
            msg.cut_tail(1); // remove final LF
            aw_message(msg.get_data());
        }
    }

    free(stamp);
    free(checksum_field);
    free(ali);
}

void NT_create_trackAliChanges_Awars(AW_root *root, AW_default properties) {
    root->awar_string(AWAR_TRACK_ALI, "???", GLOBAL.gb_main);
    root->awar_string(AWAR_TRACK_ID, GB_getenvUSER(), properties);
}

AW_window *NT_create_trackAliChanges_window(AW_root *root) {
    AW_window_simple *aws = new AW_window_simple;
    aws->init(root, "TRACK_ALI_CHANGES", "Track alignment changes");
    aws->load_xfig("trackali.fig");

    aws->at("close");
    aws->callback(AW_POPDOWN);
    aws->create_button("CLOSE", "CLOSE", "C");

    aws->at("help");
    aws->callback(makeHelpCallback("track_ali_changes.hlp"));
    aws->create_button("HELP", "HELP", "H");

    aws->at("id");
    aws->create_input_field(AWAR_TRACK_ID);

    aws->at("ali_sel");
    awt_create_ALI_selection_list(GLOBAL.gb_main, aws, AWAR_TRACK_ALI, "*=");

    aws->at("go");
    aws->callback(trackAlignmentChanges);
    aws->create_autosize_button("TRACK", "Track changes", "T");

    return aws;
}


