//
// Created by Krad on 2021/11/11.
//

#ifndef GUI_USER_H
#define GUI_USER_H

#define USER_PROPERTIES_MACRO()\
USER_READONLY_PROPERTY(UserID)\
USER_READONLY_PROPERTY(UserCode)\
USER_PROPERTY(UserName)\
USER_PROPERTY(Password)\
USER_PROPERTY(RoleID)\
USER_PROPERTY(Comment)


#include <QObject>
#include <QtCore/QCryptographicHash>

class User:public QObject {
    Q_OBJECT
public:
    static bool QueryUser(QString userID, QString Pwd);
    static bool existsUser(QString userCode);
    static QString getEncryptedPassword(const QString& password)
    {
        QByteArray bytePwd = password.toLatin1();
        QByteArray bytePwdMd5 = QCryptographicHash::hash(bytePwd, QCryptographicHash::Md5);
        return bytePwdMd5.toHex();
    }
    static User* Current(){
        return currentUser;
    }
    static bool getUser(QString userUID,User& user);
    static bool insertUser(QString UserCode,User& user);
    explicit User(QObject *parent=nullptr);
    ~User();
    QString getIndexName(){
        return "UserID";
    }
    QString getIndexValue(){
        return m_UserID;
    }
    // add properties setter and getter
    #define USER_READONLY_PROPERTY(name)\
    QString get##name(){\
        return m_##name;\
    }
    #define USER_PROPERTY(name)\
    USER_READONLY_PROPERTY(name)\
    void set##name(const QString & v)\
    {\
        if (m_##name == v) return;\
        m_##name = v;\
        mf_##name = true;\
    }
    USER_PROPERTIES_MACRO()
    #undef USER_PROPERTY
    #undef USER_READONLY_PROPERTY
    void restorePassword(const QString& original_pwd){
        m_Password = original_pwd;
        mf_Password = false;
    }
    bool submitChange();
    bool isAdmin();
    bool isEngineer();
    bool resetPassword();
    static QString getRoleName(QString RoleID);
    static QString getRoleID(QString RoleName);
    static QStringList getAllRoleName();
private:
    static User* currentUser;
    // add properties store and modify flag
    #define USER_READONLY_PROPERTY(name) QString m_##name;
    #define USER_PROPERTY(name)\
    USER_READONLY_PROPERTY(name)\
    bool mf_##name = false;
    USER_PROPERTIES_MACRO()
    #undef USER_PROPERTY
    #undef USER_READONLY_PROPERTY
    QString roleName;

};


#endif //GUI_USER_H
