/**
 *
 *  Tag.cc
 *  DO NOT EDIT. This file is generated by drogon_ctl
 *
 */

#include "Tag.h"
#include "Blog.h"
#include "BlogTag.h"
#include <drogon/utils/Utilities.h>
#include <string>

using namespace drogon;
using namespace drogon::orm;
using namespace drogon_model::postgres;

const std::string Tag::Cols::_id = "id";
const std::string Tag::Cols::_name = "name";
const std::string Tag::primaryKeyName = "id";
const bool Tag::hasPrimaryKey = true;
const std::string Tag::tableName = "tag";

const std::vector<typename Tag::MetaData> Tag::metaData_ = {
    {"id", "int32_t", "integer", 4, 1, 1, 1},
    {"name", "std::string", "character varying", 30, 0, 0, 0}};

const std::string &Tag::getColumnName(size_t index) noexcept(false)
{
    assert(index < metaData_.size());
    return metaData_[index].colName_;
}

Tag::Tag(const Row &r, const ssize_t indexOffset) noexcept
{
    if (indexOffset < 0)
    {
        if (!r["id"].isNull())
        {
            id_ = std::make_shared<int32_t>(r["id"].as<int32_t>());
        }
        if (!r["name"].isNull())
        {
            name_ = std::make_shared<std::string>(r["name"].as<std::string>());
        }
    }
    else
    {
        size_t offset = (size_t)indexOffset;
        if (offset + 2 > r.size())
        {
            LOG_FATAL << "Invalid SQL result for this model";
            return;
        }
        size_t index;
        index = offset + 0;
        if (!r[index].isNull())
        {
            id_ = std::make_shared<int32_t>(r[index].as<int32_t>());
        }
        index = offset + 1;
        if (!r[index].isNull())
        {
            name_ = std::make_shared<std::string>(r[index].as<std::string>());
        }
    }
}

Tag::Tag(const Json::Value &pJson,
         const std::vector<std::string> &pMasqueradingVector) noexcept(false)
{
    if (pMasqueradingVector.size() != 2)
    {
        LOG_ERROR << "Bad masquerading vector";
        return;
    }
    if (!pMasqueradingVector[0].empty() &&
        pJson.isMember(pMasqueradingVector[0]))
    {
        dirtyFlag_[0] = true;
        if (!pJson[pMasqueradingVector[0]].isNull())
        {
            id_ = std::make_shared<int32_t>(
                (int32_t)pJson[pMasqueradingVector[0]].asInt64());
        }
    }
    if (!pMasqueradingVector[1].empty() &&
        pJson.isMember(pMasqueradingVector[1]))
    {
        dirtyFlag_[1] = true;
        if (!pJson[pMasqueradingVector[1]].isNull())
        {
            name_ = std::make_shared<std::string>(
                pJson[pMasqueradingVector[1]].asString());
        }
    }
}

Tag::Tag(const Json::Value &pJson) noexcept(false)
{
    if (pJson.isMember("id"))
    {
        dirtyFlag_[0] = true;
        if (!pJson["id"].isNull())
        {
            id_ = std::make_shared<int32_t>((int32_t)pJson["id"].asInt64());
        }
    }
    if (pJson.isMember("name"))
    {
        dirtyFlag_[1] = true;
        if (!pJson["name"].isNull())
        {
            name_ = std::make_shared<std::string>(pJson["name"].asString());
        }
    }
}

void Tag::updateByMasqueradedJson(
    const Json::Value &pJson,
    const std::vector<std::string> &pMasqueradingVector) noexcept(false)
{
    if (pMasqueradingVector.size() != 2)
    {
        LOG_ERROR << "Bad masquerading vector";
        return;
    }
    if (!pMasqueradingVector[0].empty() &&
        pJson.isMember(pMasqueradingVector[0]))
    {
        if (!pJson[pMasqueradingVector[0]].isNull())
        {
            id_ = std::make_shared<int32_t>(
                (int32_t)pJson[pMasqueradingVector[0]].asInt64());
        }
    }
    if (!pMasqueradingVector[1].empty() &&
        pJson.isMember(pMasqueradingVector[1]))
    {
        dirtyFlag_[1] = true;
        if (!pJson[pMasqueradingVector[1]].isNull())
        {
            name_ = std::make_shared<std::string>(
                pJson[pMasqueradingVector[1]].asString());
        }
    }
}

void Tag::updateByJson(const Json::Value &pJson) noexcept(false)
{
    if (pJson.isMember("id"))
    {
        if (!pJson["id"].isNull())
        {
            id_ = std::make_shared<int32_t>((int32_t)pJson["id"].asInt64());
        }
    }
    if (pJson.isMember("name"))
    {
        dirtyFlag_[1] = true;
        if (!pJson["name"].isNull())
        {
            name_ = std::make_shared<std::string>(pJson["name"].asString());
        }
    }
}

const int32_t &Tag::getValueOfId() const noexcept
{
    static const int32_t defaultValue = int32_t();
    if (id_)
        return *id_;
    return defaultValue;
}

const std::shared_ptr<int32_t> &Tag::getId() const noexcept
{
    return id_;
}

void Tag::setId(const int32_t &pId) noexcept
{
    id_ = std::make_shared<int32_t>(pId);
    dirtyFlag_[0] = true;
}

const typename Tag::PrimaryKeyType &Tag::getPrimaryKey() const
{
    assert(id_);
    return *id_;
}

const std::string &Tag::getValueOfName() const noexcept
{
    static const std::string defaultValue = std::string();
    if (name_)
        return *name_;
    return defaultValue;
}

const std::shared_ptr<std::string> &Tag::getName() const noexcept
{
    return name_;
}

void Tag::setName(const std::string &pName) noexcept
{
    name_ = std::make_shared<std::string>(pName);
    dirtyFlag_[1] = true;
}

void Tag::setName(std::string &&pName) noexcept
{
    name_ = std::make_shared<std::string>(std::move(pName));
    dirtyFlag_[1] = true;
}

void Tag::setNameToNull() noexcept
{
    name_.reset();
    dirtyFlag_[1] = true;
}

void Tag::updateId(const uint64_t id)
{
}

const std::vector<std::string> &Tag::insertColumns() noexcept
{
    static const std::vector<std::string> inCols = {"name"};
    return inCols;
}

void Tag::outputArgs(drogon::orm::internal::SqlBinder &binder) const
{
    if (dirtyFlag_[1])
    {
        if (getName())
        {
            binder << getValueOfName();
        }
        else
        {
            binder << nullptr;
        }
    }
}

const std::vector<std::string> Tag::updateColumns() const
{
    std::vector<std::string> ret;
    if (dirtyFlag_[1])
    {
        ret.push_back(getColumnName(1));
    }
    return ret;
}

void Tag::updateArgs(drogon::orm::internal::SqlBinder &binder) const
{
    if (dirtyFlag_[1])
    {
        if (getName())
        {
            binder << getValueOfName();
        }
        else
        {
            binder << nullptr;
        }
    }
}

Json::Value Tag::toJson() const
{
    Json::Value ret;
    if (getId())
    {
        ret["id"] = getValueOfId();
    }
    else
    {
        ret["id"] = Json::Value();
    }
    if (getName())
    {
        ret["name"] = getValueOfName();
    }
    else
    {
        ret["name"] = Json::Value();
    }
    return ret;
}

Json::Value Tag::toMasqueradedJson(
    const std::vector<std::string> &pMasqueradingVector) const
{
    Json::Value ret;
    if (pMasqueradingVector.size() == 2)
    {
        if (!pMasqueradingVector[0].empty())
        {
            if (getId())
            {
                ret[pMasqueradingVector[0]] = getValueOfId();
            }
            else
            {
                ret[pMasqueradingVector[0]] = Json::Value();
            }
        }
        if (!pMasqueradingVector[1].empty())
        {
            if (getName())
            {
                ret[pMasqueradingVector[1]] = getValueOfName();
            }
            else
            {
                ret[pMasqueradingVector[1]] = Json::Value();
            }
        }
        return ret;
    }
    LOG_ERROR << "Masquerade failed";
    if (getId())
    {
        ret["id"] = getValueOfId();
    }
    else
    {
        ret["id"] = Json::Value();
    }
    if (getName())
    {
        ret["name"] = getValueOfName();
    }
    else
    {
        ret["name"] = Json::Value();
    }
    return ret;
}

bool Tag::validateJsonForCreation(const Json::Value &pJson, std::string &err)
{
    if (pJson.isMember("id"))
    {
        if (!validJsonOfField(0, "id", pJson["id"], err, true))
            return false;
    }
    if (pJson.isMember("name"))
    {
        if (!validJsonOfField(1, "name", pJson["name"], err, true))
            return false;
    }
    return true;
}

bool Tag::validateMasqueradedJsonForCreation(
    const Json::Value &pJson,
    const std::vector<std::string> &pMasqueradingVector,
    std::string &err)
{
    if (pMasqueradingVector.size() != 2)
    {
        err = "Bad masquerading vector";
        return false;
    }
    try
    {
        if (!pMasqueradingVector[0].empty())
        {
            if (pJson.isMember(pMasqueradingVector[0]))
            {
                if (!validJsonOfField(0,
                                      pMasqueradingVector[0],
                                      pJson[pMasqueradingVector[0]],
                                      err,
                                      true))
                    return false;
            }
        }
        if (!pMasqueradingVector[1].empty())
        {
            if (pJson.isMember(pMasqueradingVector[1]))
            {
                if (!validJsonOfField(1,
                                      pMasqueradingVector[1],
                                      pJson[pMasqueradingVector[1]],
                                      err,
                                      true))
                    return false;
            }
        }
    }
    catch (const Json::LogicError &e)
    {
        err = e.what();
        return false;
    }
    return true;
}

bool Tag::validateJsonForUpdate(const Json::Value &pJson, std::string &err)
{
    if (pJson.isMember("id"))
    {
        if (!validJsonOfField(0, "id", pJson["id"], err, false))
            return false;
    }
    else
    {
        err =
            "The value of primary key must be set in the json object for "
            "update";
        return false;
    }
    if (pJson.isMember("name"))
    {
        if (!validJsonOfField(1, "name", pJson["name"], err, false))
            return false;
    }
    return true;
}

bool Tag::validateMasqueradedJsonForUpdate(
    const Json::Value &pJson,
    const std::vector<std::string> &pMasqueradingVector,
    std::string &err)
{
    if (pMasqueradingVector.size() != 2)
    {
        err = "Bad masquerading vector";
        return false;
    }
    try
    {
        if (!pMasqueradingVector[0].empty() &&
            pJson.isMember(pMasqueradingVector[0]))
        {
            if (!validJsonOfField(0,
                                  pMasqueradingVector[0],
                                  pJson[pMasqueradingVector[0]],
                                  err,
                                  false))
                return false;
        }
        else
        {
            err =
                "The value of primary key must be set in the json object for "
                "update";
            return false;
        }
        if (!pMasqueradingVector[1].empty() &&
            pJson.isMember(pMasqueradingVector[1]))
        {
            if (!validJsonOfField(1,
                                  pMasqueradingVector[1],
                                  pJson[pMasqueradingVector[1]],
                                  err,
                                  false))
                return false;
        }
    }
    catch (const Json::LogicError &e)
    {
        err = e.what();
        return false;
    }
    return true;
}

bool Tag::validJsonOfField(size_t index,
                           const std::string &fieldName,
                           const Json::Value &pJson,
                           std::string &err,
                           bool isForCreation)
{
    switch (index)
    {
        case 0:
            if (pJson.isNull())
            {
                err = "The " + fieldName + " column cannot be null";
                return false;
            }
            if (isForCreation)
            {
                err = "The automatic primary key cannot be set";
                return false;
            }
            if (!pJson.isInt())
            {
                err = "Type error in the " + fieldName + " field";
                return false;
            }
            break;
        case 1:
            if (pJson.isNull())
            {
                return true;
            }
            if (!pJson.isString())
            {
                err = "Type error in the " + fieldName + " field";
                return false;
            }
            if (pJson.isString() && std::strlen(pJson.asCString()) > 30)
            {
                err = "String length exceeds limit for the " + fieldName +
                      " field (the maximum value is 30)";
                return false;
            }

            break;
        default:
            err = "Internal error in the server";
            return false;
    }
    return true;
}

std::vector<std::pair<Blog, BlogTag>> Tag::getBlogs(
    const DbClientPtr &clientPtr) const
{
    static const std::string sql =
        "select * from blog,blog_tag where blog_tag.tag_id = $1 and "
        "blog_tag.blog_id = blog.id";
    Result r(nullptr);
    {
        auto binder = *clientPtr << sql;
        binder << *id_ << Mode::Blocking >>
            [&r](const Result &result) { r = result; };
        binder.exec();
    }
    std::vector<std::pair<Blog, BlogTag>> ret;
    ret.reserve(r.size());
    for (auto const &row : r)
    {
        ret.emplace_back(
            std::pair<Blog, BlogTag>(Blog(row),
                                     BlogTag(row, Blog::getColumnNumber())));
    }
    return ret;
}

void Tag::getBlogs(
    const DbClientPtr &clientPtr,
    const std::function<void(std::vector<std::pair<Blog, BlogTag>>)> &rcb,
    const ExceptionCallback &ecb) const
{
    static const std::string sql =
        "select * from blog,blog_tag where blog_tag.tag_id = $1 and "
        "blog_tag.blog_id = blog.id";
    *clientPtr << sql << *id_ >> [rcb = std::move(rcb)](const Result &r) {
        std::vector<std::pair<Blog, BlogTag>> ret;
        ret.reserve(r.size());
        for (auto const &row : r)
        {
            ret.emplace_back(std::pair<Blog, BlogTag>(
                Blog(row), BlogTag(row, Blog::getColumnNumber())));
        }
        rcb(ret);
    } >> ecb;
}
