/*******************************************************************************
 * Copyright (c) 2023, 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 <stdexcept>
#include <string>
#include <vector>

#include <confplus/conf.h>

#include <dbpp/database.h>
#include <uuidp.h>

#pragma once

namespace blogi {

    struct AuthSource {
        std::string url;
        std::string clientName;
        std::string clientSecret;
        std::string domain;
    };

    class Config : public confplus::Config {
    public:
        Config(const std::string &path);
        ~Config();

        const std::string &getsiteurl() const;
        const std::string &getprefix() const;

        const std::string &getConfigPath() const;

        const std::string &gettemplate() const;

        const std::string &getstartpage() const;

        const std::string    buildurl(const std::string &url) const;

        const std::string &getplgdir(size_t el) const;
        size_t      getplgdirs() const;

        const std::string &getdbdriver() const;
        const std::string &getdbopts() const;

        const std::string &getAuthUrl() const;
        const std::string &getClientName() const;
        const std::string &getClientSecret() const;

        size_t              getAuthSourceCount() const;
        const AuthSource   &getAuthSource(size_t idx) const;
        const AuthSource   *findAuthSource(const std::string &domain) const;

        int               gethttpport() const;
        const std::string &gethttpaddr() const;
        int               gethttpmaxcon() const;

        const std::string &getsslcertpath() const;
        const std::string &getsslkeypath() const;
        const std::string &getsslpassword() const;

        const std::string &getDomain() const;

        const std::string &getTmpDir() const;

        const std::string &getMediaDBUrl() const;

    private:
        std::vector<std::string>  _PlgDir;
        std::string               _DBDriver;
        std::string               _DBConnection;
        std::string               _AuthUrl;
        std::string               _ClientName;
        std::string               _ClientSecret;
        std::vector<AuthSource>   _AuthSources;
        std::string               _HttpHost;
        std::string               _HttpBind;
        int                       _HttpPort;
        int                       _MaxCon;
        std::string               _HttpUrl;
        std::string               _HttpPrefix;
        std::string               _Template;
        std::string               _StartPage;
        std::string               _SSLCertpath;
        std::string               _SSLKeypath;
        std::string               _SSLPassword;
        std::string               _Domain;
        std::string               _CookieDomain;
        std::string               _TmpDir;
        std::string               _MediaDBUrl;
    };

    inline void getConfig(dbpp::Database &db,const std::string &key,std::string &value){
        dbpp::SQL sql;
        dbpp::DBResult res;
        sql << "SELECT value FROM options WHERE key='" << key.c_str() << "'";
        int rows=db.exec(sql,res);
        if(rows<1){
            throw std::runtime_error("configkey not found: " + key);
        }
        value=res[0][0];
    }

    inline void getConfig(dbpp::Database &db,const std::string &key,int &value){
        std::string buf;
        getConfig(db,key,buf);
        value=atoi(buf.c_str());
    }

    inline void getConfig(dbpp::Database &db,const std::string &key,bool &value){
        std::string buf;
        getConfig(db,key,buf);
        if(buf=="true")
            value=true;
        else
            value=false;
    }


    inline void setConfig(dbpp::Database &db,const std::string &key,const std::string &value){
        dbpp::SQL sql;
        dbpp::DBResult res;
        std::vector<char> buf;

        sql << "SELECT value FROM options WHERE key='" << key.c_str() << "'";
        int rows=db.exec(sql,res);
        sql.clear();
        if(rows<1){
            uuid::uuid id;
            id.generate();
            sql << "INSERT INTO OPTIONS (id,key,value) VALUES ('"<< id.c_str() <<"','"<< sql.escaped(buf,key.c_str()) << "','" << sql.escaped(buf,value.c_str()) <<"')";
        }else{
            sql << "UPDATE OPTIONS set value='"<<sql.escaped(buf,value.c_str()) <<"' WHERE key='"<< sql.escaped(buf,key.c_str())  <<"'";
        }
        db.exec(sql,res);
    }

};
