import { localStorageKeys } from '../../constants/localStorageKeys';
import { createSlice } from '@reduxjs/toolkit';
import { POCKET } from '../../utils/config';
const initialState = {
    actionBar: {
        tweet: POCKET.STAGE_TWEET_ACTION_BAR.TWEET,
    },
    defaultAccount: {
        name: null,
        account: null,
    },
    accounts: null,
};
const checkAddress = (obj, network, address) => Object.keys(obj).some((k) => {
    if (obj[k][network]) {
        return obj[k][network].bech32 === address;
    }
});
function saveToLocalStorage(state) {
    const { defaultAccount, accounts } = state;
    defaultAccount &&
        localStorage.setItem(localStorageKeys.pocket.POCKET, JSON.stringify({
            [defaultAccount.name]: defaultAccount.account,
        }));
    accounts &&
        localStorage.setItem(localStorageKeys.pocket.POCKET_ACCOUNT, JSON.stringify(accounts));
}
const slice = createSlice({
    name: 'pocket',
    initialState,
    reducers: {
        setDefaultAccount: (state, { payload: { name, account }, }) => {
            var _a;
            state.defaultAccount = {
                name,
                account: account || ((_a = state.accounts) === null || _a === void 0 ? void 0 : _a[name]) || null,
            };
            saveToLocalStorage(state);
        },
        setAccounts: (state, { payload }) => {
            state.accounts = payload;
            saveToLocalStorage(state);
        },
        setStageTweetActionBar: (state, { payload }) => {
            state.actionBar.tweet = payload;
        },
        deleteAddress: (state, { payload }) => {
            if (state.accounts) {
                Object.keys(state.accounts).forEach((accountKey) => {
                    Object.keys(state.accounts[accountKey]).forEach((networkKey) => {
                        var _a, _b, _c;
                        if (state.accounts[accountKey][networkKey].bech32 === payload) {
                            delete state.accounts[accountKey][networkKey];
                            if (Object.keys(state.accounts[accountKey]).length === 0) {
                                delete state.accounts[accountKey];
                            }
                            if (((_c = (_b = (_a = state.defaultAccount) === null || _a === void 0 ? void 0 : _a.account) === null || _b === void 0 ? void 0 : _b.cyber) === null || _c === void 0 ? void 0 : _c.bech32) === payload) {
                                const entries = Object.entries(state.accounts);
                                const entryCyber = entries.find(([, value]) => { var _a; return (_a = value.cyber) === null || _a === void 0 ? void 0 : _a.bech32; });
                                if (entryCyber) {
                                    state.defaultAccount = {
                                        name: entryCyber[0],
                                        account: entryCyber[1],
                                    };
                                }
                                else {
                                    state.defaultAccount = {
                                        name: null,
                                        account: null,
                                    };
                                }
                            }
                            saveToLocalStorage(state);
                        }
                    });
                });
            }
        },
    },
});
export const selectCurrentAddress = (store) => { var _a, _b; return (_b = (_a = store.pocket.defaultAccount.account) === null || _a === void 0 ? void 0 : _a.cyber) === null || _b === void 0 ? void 0 : _b.bech32; };
export const { setDefaultAccount, setAccounts, setStageTweetActionBar, deleteAddress, } = slice.actions;
export default slice.reducer;
export const initPocket = () => (dispatch) => {
    let defaultAccounts = null;
    let defaultAccountsKeys = null;
    let accountsTemp = null;
    const localStoragePocketAccount = localStorage.getItem(localStorageKeys.pocket.POCKET_ACCOUNT);
    const localStoragePocket = localStorage.getItem(localStorageKeys.pocket.POCKET);
    if (localStoragePocket !== null) {
        const localStoragePocketData = JSON.parse(localStoragePocket);
        const keyPocket = Object.keys(localStoragePocketData)[0];
        const accountPocket = Object.values(localStoragePocketData)[0];
        defaultAccounts = accountPocket;
        defaultAccountsKeys = keyPocket;
    }
    if (localStoragePocketAccount !== null) {
        const localStoragePocketAccountData = JSON.parse(localStoragePocketAccount);
        if (localStoragePocket === null) {
            const keys0 = Object.keys(localStoragePocketAccountData)[0];
            localStorage.setItem(localStorageKeys.pocket.POCKET, JSON.stringify({ [keys0]: localStoragePocketAccountData[keys0] }));
            defaultAccounts = localStoragePocketAccountData[keys0];
            defaultAccountsKeys = keys0;
        }
        else if (defaultAccountsKeys !== null) {
            accountsTemp = Object.assign({ [defaultAccountsKeys]: localStoragePocketAccountData[defaultAccountsKeys] || undefined }, localStoragePocketAccountData);
        }
    }
    else {
        localStorage.removeItem(localStorageKeys.pocket.POCKET);
        localStorage.removeItem(localStorageKeys.pocket.POCKET_ACCOUNT);
    }
    defaultAccountsKeys &&
        defaultAccounts &&
        dispatch(setDefaultAccount({
            name: defaultAccountsKeys,
            account: defaultAccounts,
        }));
    accountsTemp &&
        Object.keys(accountsTemp).forEach((key) => {
            if (!accountsTemp[key] || Object.keys(accountsTemp[key]).length === 0) {
                delete accountsTemp[key];
            }
        });
    accountsTemp && dispatch(setAccounts(accountsTemp));
};
const defaultNameAccount = () => {
    let key = 'Account 1';
    let count = 1;
    const localStorageCount = localStorage.getItem('count');
    if (localStorageCount !== null) {
        const dataCount = JSON.parse(localStorageCount);
        count = parseFloat(dataCount);
        key = `Account ${count}`;
    }
    localStorage.setItem('count', JSON.stringify(count + 1));
    return key;
};
export const addAddressPocket = (accounts) => (dispatch) => {
    const key = accounts.name || defaultNameAccount();
    let dataPocketAccount = null;
    let valueObj = {};
    let pocketAccount = {};
    const localStorageStory = localStorage.getItem(localStorageKeys.pocket.POCKET_ACCOUNT);
    if (localStorageStory !== null) {
        dataPocketAccount = JSON.parse(localStorageStory);
        valueObj = Object.values(dataPocketAccount);
    }
    const isAdded = !checkAddress(valueObj, 'cyber', accounts.bech32);
    if (!isAdded) {
        return;
    }
    const cyberAccounts = {
        cyber: accounts,
    };
    if (localStorageStory !== null) {
        pocketAccount = Object.assign({ [key]: cyberAccounts }, dataPocketAccount);
    }
    else {
        pocketAccount = { [key]: cyberAccounts };
    }
    if (Object.keys(pocketAccount).length > 0) {
        dispatch(setAccounts(pocketAccount));
        if (accounts.keys !== 'read-only') {
            dispatch(setDefaultAccount({ name: key, account: cyberAccounts }));
        }
    }
};
//# sourceMappingURL=pocket.js.map