/*******************************************************************************
Copyright (c) 2024, 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 <iostream>
#include <cstring>
#include <algorithm>

#include "cookie.h"
#include "i18n.h"

void blogi::CookieBanner::init(){
    dbpp::SQL sql;
    dbpp::DBResult res;

    sql << "CREATE TABLE IF NOT EXISTS cookie_rules("
    <<   "id " << dbconn.getUUIDType(sql) << ","
    <<   "name varchar(255),"
    <<   "description text,"
    <<   "required bool,"
    <<   "PRIMARY KEY (id)"
    << ");";

    dbconn.exec(sql,res);
}

bool blogi::CookieBanner::getPermission(const std::string &sessionid,const char* cookieid){
  std::string ret;
  try{
      session.getSessionData(sessionid,cookieid,ret);
  }catch(...){
      return false;
  }
  if(ret=="True")
      return true;
  return false;
}

void blogi::CookieBanner::setPermission(const std::string &sessionid, const char* cookieid, bool perm){
  if(perm)
      session.addSessionData(sessionid,cookieid,"True");
  else
      session.addSessionData(sessionid,cookieid,"False");
}

void blogi::CookieBanner::addRule(uuid::uuid id,const char* cookname, const char* desc,bool req){
    dbpp::SQL sql;
    dbpp::DBResult res;

    sql << "INSERT INTO cookie_rules (id,name,description,required) VALUES"
         <<  "('" << id.c_str() << "','"<< cookname << "','" << desc << "','" << req << "');";
    try{
        dbconn.exec(sql,res);
    }catch(...){
          std::cerr << "Rule already exists!" << std::endl;
    }
}

void blogi::print(dbpp::Database &db,const std::string &lang,const std::string &curl,libhtmlpp::HtmlElement& page,libhtmlpp::HtmlElement cookietpl){
    dbpp::DBResult res;
    dbpp::SQL sql;

    libhtmlpp::HtmlTable ctable;
    libhtmlpp::HtmlElement cookel=cookietpl.getElementbyID("cookiebanner"),cookset;

    sql << "SELECT id,name,description,required FROM cookie_rules;";

    int ret=db.exec(sql,res);

    libhtmlpp::HtmlString input;

    for(int i=0; i<ret; ++i ){
        input << "<label for=\"" << res[i][0] << "\">"<< tr(lang,res[i][1]).c_str() << "</label>"
                 << "<input id=\"" << res[i][0] << "\" name=\""<< res[i][0] << "\" ";
        if(strcmp(res[i][3],"t")==0){
             input << "onclick=\"return false;\"";
        }
        input << " checked=\"\" type=\"checkbox\">";
        ctable << (libhtmlpp::HtmlTable::Row() << input << tr(lang,res[i][2]).c_str());
        input.clear();
   }

  ctable.insert(&cookset);

  if(cookel.getElementbyID("cookiesettings")){
     cookel.getElementbyID("cookiesettings")->setAttribute("action",curl.c_str());
     cookel.getElementbyID("cookiesettings")->appendChild(&cookset);
  }

  libhtmlpp::HtmlElement *idx=page.getElementbyTag("body");

  if(idx)
      idx->appendChild(cookel);
}
