/*******************************************************************************
Copyright (c) 2025, Jan Koester jan.koester@gmx.net
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 the <organization> 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 COPYRIGHT HOLDERS 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 <COPYRIGHT HOLDER> 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.
*******************************************************************************/

#include <sstream>
#include <iostream>
#include <cstring>

#include <tinyxml2.h>
#include <htmlpp/html.h>

#include "plugin.h"

extern "C" {
    namespace blogi::webedit {

        class Video : public EditPlugin {
        private:
            std::string src;
            std::string width      = "100%";
            std::string height     = "auto";
            std::string mediaId    = "";
            std::string mediaExt   = "mp4";
            bool        controls   = true;
            bool        playOnHover = false;

            // Mobile overrides
            std::string m_width    = "";
            std::string m_height   = "";

            // Visibility
            bool hidden   = false;
            bool m_hidden  = false;

            // Custom CSS
            std::string customCss = "";

        public:
            Video() {
                Type = "a77fbcd4-5i98-7h6i-d7f9-2i89g4e989f7";
            }

            virtual ~Video() = default;

            const std::string getName() const override {
                return "Video";
            }

            const std::string getAuthor() const override {
                return "Jan Koester";
            }

            const std::string getVersion() const override {
                return "1.0";
            }

            void logError(const std::string& message) override {
                std::cerr << "VideoPlugin Error (" << getInstanceId().c_str() << "): " << message << std::endl;
            }

            // --- UI Settings ---
            void Settings(libhttppp::HttpRequest &curreq, libhtmlpp::HtmlElement &settings) override {
                libhtmlpp::HtmlElement title("h3");
                title.appendChild(libhtmlpp::TextElement("Video Settings"));
                settings.appendChild(title);

                // Source URL
                libhtmlpp::HtmlElement srcLabel("label");
                srcLabel.appendChild(libhtmlpp::TextElement("Video URL: "));
                settings.appendChild(srcLabel);
                libhtmlpp::HtmlElement srcInput("input");
                srcInput.setAttribute("type", "text");
                srcInput.setAttribute("name", "src");
                srcInput.setAttribute("value", src.c_str());
                srcInput.setAttribute("placeholder", "/path/to/video.mp4");
                settings.appendChild(srcInput);

                // Width
                libhtmlpp::HtmlElement wLabel("label");
                wLabel.appendChild(libhtmlpp::TextElement("Width: "));
                settings.appendChild(wLabel);
                libhtmlpp::HtmlElement wInput("input");
                wInput.setAttribute("type", "text");
                wInput.setAttribute("name", "width");
                wInput.setAttribute("value", width.c_str());
                settings.appendChild(wInput);

                // Height
                libhtmlpp::HtmlElement hLabel("label");
                hLabel.appendChild(libhtmlpp::TextElement("Height: "));
                settings.appendChild(hLabel);
                libhtmlpp::HtmlElement hInput("input");
                hInput.setAttribute("type", "text");
                hInput.setAttribute("name", "height");
                hInput.setAttribute("value", height.c_str());
                settings.appendChild(hInput);

                // Controls
                libhtmlpp::HtmlElement ctrlLabel("label");
                ctrlLabel.appendChild(libhtmlpp::TextElement("Show Controls: "));
                settings.appendChild(ctrlLabel);
                libhtmlpp::HtmlElement ctrlInput("input");
                ctrlInput.setAttribute("type", "checkbox");
                ctrlInput.setAttribute("name", "controls");
                if (controls) ctrlInput.setAttribute("checked", "checked");
                settings.appendChild(ctrlInput);

                // Media file extension
                libhtmlpp::HtmlElement extLabel("label");
                extLabel.appendChild(libhtmlpp::TextElement("Format: "));
                settings.appendChild(extLabel);
                libhtmlpp::HtmlElement extSelect("select");
                extSelect.setAttribute("name", "media_ext");
                const char* exts[] = {"mp4", "webm", "ogg", "mov", "avi"};
                for (const char* e : exts) {
                    libhtmlpp::HtmlElement opt("option");
                    opt.setAttribute("value", e);
                    if (mediaExt == e) opt.setAttribute("selected", "selected");
                    opt.appendChild(libhtmlpp::TextElement(e));
                    extSelect.appendChild(opt);
                }
                settings.appendChild(extSelect);
            }

            // --- JSON API ---
            void JsonApi(json_object *request, json_object *response) override {
                if (request == nullptr) {
                    logError("Invalid JSON request received (nullptr).");
                    return;
                }

                json_object *action_obj = nullptr;
                const char *action = nullptr;

                if (json_object_object_get_ex(request, "action", &action_obj)) {
                    action = json_object_get_string(action_obj);
                }

                if (action == nullptr || action[0] == '\0') {
                    logError("No action specified in JsonApi request.");
                    return;
                }

                if (strcmp(action, "modify_bulk") == 0) {
                    json_object *props_obj = nullptr;
                    if (json_object_object_get_ex(request, "properties", &props_obj)) {
                        const char *json_str = json_object_to_json_string_ext(props_obj, JSON_C_TO_STRING_NOSLASHESCAPE);
                        if (json_str) {
                            fromPropertiesJson(json_str);
                        }
                    }
                } else if (strcmp(action, "read") == 0) {
                    json_object *result_obj = json_object_new_object();
                    json_object_object_add(result_obj, "properties", json_object_new_string(toPropertiesJson().c_str()));
                    if (response) {
                        json_object_object_add(response, "data", result_obj);
                    }
                } else if (strcmp(action, "get_schema") == 0) {
                    if (response) {
                        json_object_object_add(response, "schema", getSchemaJson());
                    }
                }

                if (response != nullptr) {
                    json_object_object_add(response, "status", json_object_new_string("success"));
                    json_object_object_add(response, "plugin_type", json_object_new_string("Video"));
                }
            }

            // --- XML Persistence ---
            tinyxml2::XMLElement* toXmlObject(tinyxml2::XMLDocument* doc) override {
                tinyxml2::XMLElement* element = doc->NewElement(getName().c_str());
                element->SetAttribute("instance_id", getInstanceId().c_str());
                element->SetAttribute("type_id", getTypeId().c_str());
                element->SetAttribute("src", src.c_str());
                element->SetAttribute("width", width.c_str());
                element->SetAttribute("height", height.c_str());
                element->SetAttribute("media_id", mediaId.c_str());
                element->SetAttribute("media_ext", mediaExt.c_str());
                element->SetAttribute("controls", controls ? "true" : "false");
                element->SetAttribute("play_on_hover", playOnHover ? "true" : "false");

                // Mobile overrides
                element->SetAttribute("m_width", m_width.c_str());
                element->SetAttribute("m_height", m_height.c_str());

                // Visibility
                element->SetAttribute("hidden", hidden ? "true" : "false");
                element->SetAttribute("m_hidden", m_hidden ? "true" : "false");

                if (!customCss.empty()) {
                    tinyxml2::XMLElement* cssEl = doc->NewElement("CustomCss");
                    cssEl->SetText(customCss.c_str());
                    element->InsertEndChild(cssEl);
                }
                return element;
            }

            void fromXmlObject(tinyxml2::XMLElement* xml_data) override {
                const char* val = nullptr;

                val = xml_data->Attribute("src");           if (val) src = val;
                val = xml_data->Attribute("width");         if (val) width = val;
                val = xml_data->Attribute("height");        if (val) height = val;
                val = xml_data->Attribute("media_id");      if (val) mediaId = val;
                val = xml_data->Attribute("media_ext");     if (val) mediaExt = val;

                val = xml_data->Attribute("controls");
                if (val) controls = (strcmp(val, "true") == 0);

                val = xml_data->Attribute("play_on_hover");
                if (val) playOnHover = (strcmp(val, "true") == 0);

                // Mobile overrides
                val = xml_data->Attribute("m_width");       if (val) m_width = val;
                val = xml_data->Attribute("m_height");      if (val) m_height = val;

                // Visibility
                val = xml_data->Attribute("hidden");
                if (val) hidden = (strcmp(val, "true") == 0);
                val = xml_data->Attribute("m_hidden");
                if (val) m_hidden = (strcmp(val, "true") == 0);

                tinyxml2::XMLElement* cssEl = xml_data->FirstChildElement("CustomCss");
                if (cssEl) {
                    const char* cssVal = cssEl->GetText();
                    if (cssVal) customCss = cssVal;
                }
            }

            // --- JSON Properties Helpers ---
            std::string toPropertiesJson() {
                json_object *obj = json_object_new_object();
                json_object_object_add(obj, "src", json_object_new_string(src.c_str()));
                json_object_object_add(obj, "width", json_object_new_string(width.c_str()));
                json_object_object_add(obj, "height", json_object_new_string(height.c_str()));
                json_object_object_add(obj, "media_id", json_object_new_string(mediaId.c_str()));
                json_object_object_add(obj, "media_ext", json_object_new_string(mediaExt.c_str()));
                json_object_object_add(obj, "controls", json_object_new_boolean(controls));
                json_object_object_add(obj, "play_on_hover", json_object_new_boolean(playOnHover));
                json_object_object_add(obj, "m_width", json_object_new_string(m_width.c_str()));
                json_object_object_add(obj, "m_height", json_object_new_string(m_height.c_str()));
                json_object_object_add(obj, "hidden", json_object_new_boolean(hidden));
                json_object_object_add(obj, "m_hidden", json_object_new_boolean(m_hidden));
                json_object_object_add(obj, "custom_css", json_object_new_string(customCss.c_str()));
                std::string result = json_object_to_json_string_ext(obj, JSON_C_TO_STRING_NOSLASHESCAPE);
                json_object_put(obj);
                return result;
            }

            void fromPropertiesJson(const std::string &json) {
                json_object *obj = json_tokener_parse(json.c_str());
                if (!obj) return;

                json_object *val_obj = nullptr;
                const char *val = nullptr;

                if (json_object_object_get_ex(obj, "src", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) src = val;
                }
                if (json_object_object_get_ex(obj, "width", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) width = val;
                }
                if (json_object_object_get_ex(obj, "height", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) height = val;
                }
                if (json_object_object_get_ex(obj, "media_id", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) mediaId = val;
                }
                if (json_object_object_get_ex(obj, "media_ext", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) mediaExt = val;
                }
                if (json_object_object_get_ex(obj, "controls", &val_obj)) {
                    if (json_object_is_type(val_obj, json_type_string)) {
                        const char *s = json_object_get_string(val_obj);
                        controls = (s && (strcmp(s, "true") == 0 || strcmp(s, "1") == 0));
                    } else {
                        controls = json_object_get_boolean(val_obj);
                    }
                }
                if (json_object_object_get_ex(obj, "play_on_hover", &val_obj)) {
                    if (json_object_is_type(val_obj, json_type_string)) {
                        const char *s = json_object_get_string(val_obj);
                        playOnHover = (s && (strcmp(s, "true") == 0 || strcmp(s, "1") == 0));
                    } else {
                        playOnHover = json_object_get_boolean(val_obj);
                    }
                }
                if (json_object_object_get_ex(obj, "m_width", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) m_width = val;
                }
                if (json_object_object_get_ex(obj, "m_height", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) m_height = val;
                }
                if (json_object_object_get_ex(obj, "hidden", &val_obj)) {
                    if (json_object_is_type(val_obj, json_type_string)) {
                        const char *s = json_object_get_string(val_obj);
                        hidden = (s && (strcmp(s, "true") == 0 || strcmp(s, "1") == 0));
                    } else {
                        hidden = json_object_get_boolean(val_obj);
                    }
                }
                if (json_object_object_get_ex(obj, "m_hidden", &val_obj)) {
                    if (json_object_is_type(val_obj, json_type_string)) {
                        const char *s = json_object_get_string(val_obj);
                        m_hidden = (s && (strcmp(s, "true") == 0 || strcmp(s, "1") == 0));
                    } else {
                        m_hidden = json_object_get_boolean(val_obj);
                    }
                }
                if (json_object_object_get_ex(obj, "custom_css", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) customCss = val;
                }

                json_object_put(obj);
            }

            // --- Schema ---
            static json_object* getSchemaJson() {
                json_object *arr = json_object_new_array();
                auto addField = [&](const char *key, const char *label, const char *type,
                                    const char *placeholder = nullptr, const char *target = "all",
                                    json_object *options = nullptr) {
                    json_object *f = json_object_new_object();
                    json_object_object_add(f, "key", json_object_new_string(key));
                    json_object_object_add(f, "label", json_object_new_string(label));
                    json_object_object_add(f, "type", json_object_new_string(type));
                    if (placeholder) json_object_object_add(f, "placeholder", json_object_new_string(placeholder));
                    json_object_object_add(f, "target", json_object_new_string(target));
                    if (options) json_object_object_add(f, "options", options);
                    json_object_array_add(arr, f);
                };
                auto mkOpts = [](std::initializer_list<const char*> vals) {
                    json_object *a = json_object_new_array();
                    for (auto v : vals) json_object_array_add(a, json_object_new_string(v));
                    return a;
                };
                addField("media_id", "Media (from MediaDB)", "media_browse");
                addField("media_ext", "Format", "select", nullptr, "all", mkOpts({"mp4", "webm", "ogg", "mov", "avi"}));
                addField("src", "Video Path (manual)", "text", "/path/to/video.mp4");
                addField("width", "CSS Width", "text", "100%", "desktop");
                addField("height", "CSS Height", "text", "auto", "desktop");
                addField("controls", "Show Play Controls", "checkbox");
                addField("play_on_hover", "Play on Mouse Over", "checkbox");
                addField("hidden", "Hidden", "checkbox", nullptr, "desktop");
                {
                    json_object *hf = json_object_array_get_idx(arr, json_object_array_length(arr) - 1);
                    json_object_object_add(hf, "default", json_object_new_boolean(false));
                }
                addField("custom_css", "Custom CSS", "textarea", ".we-xxx { color: red; }");
                return arr;
            }

            // --- HTML Rendering ---
            void Render(libhtmlpp::HtmlElement &el) const override {
                libhtmlpp::HtmlElement wrapper("div");

                std::string responsiveClass = std::string("we-") + getInstanceId().c_str();

                std::string renderSrc = src;
                const std::string &pfx = getPrefix();
                if (!renderSrc.empty() && renderSrc[0] == '/' && !pfx.empty() && pfx != "/") {
                    if (renderSrc.length() < pfx.length() || renderSrc.substr(0, pfx.length()) != pfx) {
                        renderSrc = pfx + renderSrc;
                    }
                }

                libhtmlpp::HtmlElement video("video");
                video.setAttribute("src", renderSrc.c_str());
                video.setAttribute("class", responsiveClass.c_str());

                if (controls) {
                    video.setAttribute("controls", "controls");
                } else if (playOnHover) {
                    video.setAttribute("onclick",
                        "if(this.dataset.hoverPlay==='1'){"
                            "this.pause();this.dataset.hoverPlay='0';"
                        "}else if(this.paused){"
                            "this.dataset.clickPlay='1';this.dataset.hoverPlay='0';this.play();"
                        "}else{"
                            "this.dataset.clickPlay='0';this.pause();"
                        "}");
                    video.setAttribute("onmouseenter",
                        "if(this.dataset.clickPlay!=='1'&&this.paused){"
                            "this.dataset.hoverPlay='1';this.play();"
                        "}");
                    video.setAttribute("onmouseleave",
                        "if(this.dataset.hoverPlay==='1'){"
                            "this.pause();this.dataset.hoverPlay='0';"
                        "}");
                } else {
                    video.setAttribute("onclick", "if(this.paused){this.play();}else{this.pause();}");
                }

                std::string style;
                style += "width: " + width + ";";
                style += " height: " + height + ";";
                style += " display: block;";
                if (hidden) style += " display: none;";
                video.setAttribute("style", style.c_str());

                // Mobile responsive overrides via media query
                std::string mobileCSS;
                if (!m_width.empty()) mobileCSS += " width: " + m_width + " !important;";
                if (!m_height.empty()) mobileCSS += " height: " + m_height + " !important;";
                if (m_hidden) mobileCSS += " display: none !important;";
                else if (hidden) mobileCSS += " display: block !important;";

                if (!mobileCSS.empty()) {
                    libhtmlpp::HtmlElement styleTag("style");
                    std::string mediaRule = "@media (max-width: 768px) { ." + responsiveClass + " {" + mobileCSS + " } }";
                    styleTag.appendChild(libhtmlpp::TextElement(mediaRule.c_str()));
                    el.appendChild(styleTag);
                }

                if (!customCss.empty()) {
                    libhtmlpp::HtmlElement cssStyle("style");
                    cssStyle.appendChild(libhtmlpp::TextElement(customCss.c_str()));
                    el.appendChild(cssStyle);
                }

                wrapper.appendChild(video);
                el.appendChild(wrapper);
            }

            // --- Element Management (Video is a leaf) ---
            bool canHaveChildren() const override { return false; }
            bool haveChilds() override { return false; }

            void setChildElement(const EditPlugin &) override {
                logError("Video cannot have children.");
            }
            void unsetChildElement(const EditPlugin &) override {
                logError("Video cannot have children.");
            }
            void addNextElement(const EditPlugin &) override {
                logError("Video does not support addNextElement.");
            }
            void remNextElement(const EditPlugin &) override {
                logError("Video does not support remNextElement.");
            }
        };
    };
}

// --- Factory Functions ---
EXPORT blogi::webedit::Video* create() {
    return new blogi::webedit::Video();
}

EXPORT void destroy(blogi::webedit::Video* p) {
    delete p;
}
