/**
 * Copyright (c) 2007-2012, Timothy Stack
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * * Neither the name of Timothy Stack nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef textfile_sub_source_hh
#define textfile_sub_source_hh

#include <deque>
#include <memory>
#include <unordered_set>
#include <vector>

#include "base/attr_line.hh"
#include "base/file_range.hh"
#include "document.sections.hh"
#include "filter_observer.hh"
#include "hasher.hh"
#include "logfile.hh"
#include "plain_text_source.hh"
#include "text_overlay_menu.hh"
#include "textview_curses.hh"

class textfile_header_overlay;

class textfile_sub_source
    : public text_sub_source
    , public vis_location_history
    , public text_time_translator
    , public text_accel_source
    , public text_anchors {
public:
    textfile_sub_source() { this->tss_supports_filtering = true; }

    bool empty() const override { return this->tss_files.empty(); }

    size_t size() const { return this->tss_files.size(); }

    size_t text_line_count() override;

    size_t text_line_width(textview_curses& curses) override;

    line_info text_value_for_line(textview_curses& tc,
                                  int line,
                                  std::string& value_out,
                                  line_flags_t flags) override;

    void text_attrs_for_line(textview_curses& tc,
                             int row,
                             string_attrs_t& value_out) override;

    size_t text_size_for_line(textview_curses& tc,
                              int line,
                              line_flags_t flags) override;

    std::shared_ptr<logfile> current_file() const
    {
        if (this->tss_files.empty()) {
            return nullptr;
        }

        return this->tss_files.front()->fvs_file;
    }

    void to_front(const std::shared_ptr<logfile>& lf);

    bool to_front(const std::string& filename);

    void set_top_from_off(file_off_t off);

    void rotate_left();

    void rotate_right();

    void remove(const std::shared_ptr<logfile>& lf);

    void push_back(const std::shared_ptr<logfile>& lf);

    class scan_callback {
    public:
        virtual ~scan_callback() = default;

        virtual void closed_files(
            const std::vector<std::shared_ptr<logfile>>& files) = 0;
        virtual void promote_file(const std::shared_ptr<logfile>& lf) = 0;
        virtual void scanned_file(const std::shared_ptr<logfile>& lf) = 0;
        virtual void renamed_file(const std::shared_ptr<logfile>& lf) = 0;
    };

    struct rescan_result_t {
        size_t rr_new_data{0};
        bool rr_scan_completed{true};
        bool rr_rescan_needed{false};
    };

    rescan_result_t rescan_files(scan_callback& callback,
                                 std::optional<ui_clock::time_point> deadline
                                 = std::nullopt);

    void text_filters_changed() override;

    void text_mark(const bookmark_type_t* bm,
                   vis_line_t line,
                   bool added) override;

    void text_clear_marks(const bookmark_type_t* bm) override;

    void text_update_marks(vis_bookmarks& bm) override;

    int get_filtered_count() const override;

    int get_filtered_count_for(size_t filter_index) const override;

    std::optional<text_format_t> get_text_format() const override;

    std::optional<location_history*> get_location_history() override
    {
        return this;
    }

    void text_crumbs_for_line(int line,
                              std::vector<breadcrumb::crumb>& crumbs) override;

    std::optional<vis_line_t> row_for_anchor(const std::string& id) override;

    std::optional<std::string> anchor_for_row(vis_line_t vl) override;

    std::optional<vis_line_t> adjacent_anchor(vis_line_t vl,
                                              direction dir) override;

    std::unordered_set<std::string> get_anchors() override;

    std::optional<vis_line_t> row_for_time(timeval time_bucket) override;

    std::optional<row_info> time_for_row(vis_line_t row) override;

    void quiesce() override;

    bool is_time_offset_supported() const override
    {
        const auto lf = this->current_file();
        if (lf != nullptr && lf->has_line_metadata()) {
            return true;
        }

        return false;
    }

    logline* text_accel_get_line(vis_line_t vl) override;

    void scroll_invoked(textview_curses* tc) override;

    enum class view_mode {
        raw,
        rendered,
    };

    void set_view_mode(view_mode vm);

    view_mode get_effective_view_mode() const;

    bool tss_apply_default_init_location{false};

    struct file_view_state {
        explicit file_view_state(const std::shared_ptr<logfile>& f)
            : fvs_file(f)
        {
        }

        bool operator==(const std::shared_ptr<logfile>& lf) const
        {
            return this->fvs_file == lf;
        }

        void save_from(textview_curses& tc)
        {
            this->fvs_top = tc.get_top();
            this->fvs_selection = tc.get_selection();
            this->fvs_bookmarks.swap(tc.get_bookmarks());
        }

        void load_into(textview_curses& tc)
        {
            tc.get_bookmarks().swap(this->fvs_bookmarks);
            if (this->fvs_selection.has_value()) {
                tc.set_selection(this->fvs_selection.value());
            }
            tc.set_top(this->fvs_top);
        }

        size_t text_line_count(view_mode mode) const;

        size_t text_line_width(view_mode mode, textview_curses& tc) const;

        std::optional<vis_line_t> row_for_anchor(view_mode mode,
                                                 const std::string& id);

        std::shared_ptr<logfile> fvs_file;
        vis_line_t fvs_top{0};
        std::optional<vis_line_t> fvs_selection;
        vis_bookmarks fvs_bookmarks{vis_bookmarks_t::create_array()};

        bookmarks<uint32_t>::type fvs_content_marks{
            bookmarks<uint32_t>::create_array()};

        time_t fvs_mtime{0};
        file_ssize_t fvs_file_size{0};
        file_off_t fvs_file_indexed_size{0};
        std::string fvs_error;
        std::unique_ptr<plain_text_source> fvs_text_source;
        lnav::document::metadata fvs_metadata;
        bool fvs_consumed_init_location{false};
    };

    using file_iterator
        = std::deque<std::shared_ptr<file_view_state>>::iterator;
    using const_file_iterator
        = std::deque<std::shared_ptr<file_view_state>>::const_iterator;

    std::deque<std::shared_ptr<file_view_state>>& get_file_states()
    {
        return this->tss_files;
    }

    void copy_bookmarks_to_current_file()
    {
        if (!this->tss_files.empty() && this->tss_view != nullptr) {
            auto& front = this->tss_files.front();
            front->fvs_bookmarks[&textview_curses::BM_USER]
                = this->tss_view->get_bookmarks()[&textview_curses::BM_USER];
            front->fvs_bookmarks[&textview_curses::BM_STICKY]
                = this->tss_view->get_bookmarks()[&textview_curses::BM_STICKY];
        }
    }

private:
    friend textfile_header_overlay;

    void detach_observer(std::shared_ptr<logfile> lf)
    {
        auto* lfo = (line_filter_observer*) lf->get_logline_observer();
        lf->set_logline_observer(nullptr);
        delete lfo;
    }

    void move_to_init_location(file_iterator& iter);

    file_iterator current_file_state() { return this->tss_files.begin(); }

    const_file_iterator current_file_state() const
    {
        return this->tss_files.cbegin();
    }

    std::deque<std::shared_ptr<file_view_state>> tss_files;
    size_t tss_line_indent_size{0};
    bool tss_last_scan_aborted{false};
    attr_line_t tss_hex_line;
    string_attrs_t tss_plain_line_attrs;
    int64_t tss_content_line{0};
    view_mode tss_view_mode{view_mode::rendered};
};

class textfile_header_overlay : public text_overlay_menu {
public:
    explicit textfile_header_overlay(textfile_sub_source* src,
                                     text_sub_source* log_src);

    bool list_static_overlay(const listview_curses& lv,
                             media_t media,
                             int y,
                             int bottom,
                             attr_line_t& value_out) override;

    std::optional<attr_line_t> list_header_for_overlay(
        const listview_curses& lv, media_t media, vis_line_t line) override;

    void list_value_for_overlay(const listview_curses& lv,
                                vis_line_t line,
                                std::vector<attr_line_t>& value_out) override;

private:
    textfile_sub_source* tho_src;
    text_sub_source* tho_log_src;
    std::vector<attr_line_t> tho_static_lines;
    hasher::array_t tho_filter_state;
    attr_line_t tho_hex_line_header;
};

#endif
