import { c } from 'ttag';
import { computeKeyPassword } from 'pm-srp';
import { decryptPrivateKey } from 'pmcrypto';
import { getPrimaryKeyWithSalt } from 'proton-shared/lib/keys/keys';

export const getAuthTypes = ({ '2FA': { Enabled }, PasswordMode } = {}) => {
    return {
        hasTotp: Enabled & 1,
        hasU2F: Enabled & 2,
        hasUnlock: PasswordMode !== 1
    };
};

export const getErrorText = (error) => {
    if (error.name === 'PasswordError') {
        return c('Error').t`Incorrect decryption password`;
    }
    if (error.data && error.data.Error) {
        return error.data.Error;
    }
    return error.message;
};

export const handleUnlockKey = async (User, KeySalts, rawKeyPassword) => {
    const { KeySalt, PrivateKey } = getPrimaryKeyWithSalt(User.Keys, KeySalts);

    // Support for versions without a key salt.
    const keyPassword = KeySalt ? await computeKeyPassword(rawKeyPassword, KeySalt) : rawKeyPassword;
    const primaryKey = await decryptPrivateKey(PrivateKey, keyPassword).catch(() => {
        const error = new Error('Wrong private key password');
        error.name = 'PasswordError';
        throw error;
    });

    return { primaryKey, keyPassword };
};

@@ -178,16 +178,150 @@
 s/keys';
+%0Aimport %7B TWO_FA_FLAGS, PASSWORD_MODE %7D from 'proton-shared/lib/constants';%0Aimport %7B hasBit %7D from 'proton-shared/lib/helpers/bitset';
 %0A%0Aexport
@@ -425,48 +425,93 @@
 tp: 
-Enabled & 1,%0A        hasU2F: Enabled & 2
+hasBit(Enabled, TWO_FA_FLAGS.TOTP),%0A        hasU2F: hasBit(Enabled, TWO_FA_FLAGS.U2F)
 ,%0A  
@@ -544,13 +544,38 @@
 ode 
-!== 1
+=== PASSWORD_MODE.TWO_PASSWORD
 %0A   

Use login constants