import { combineReducers } from 'redux';

const initialWeb3State = {
    web3: null,
    isLoading: false,
    error: null
}

function web3(state = initialWeb3State, action) {
    switch(action.type) {
        case 'CREATE_WEB3_STARTED':
            return {...state, isLoading: true};
        case 'CREATE_WEB3_SUCCEEDED':
            return {...state, web3: action.web3, isLoading: false};
        case 'CREATE_WEB3_FAILED':
            return {...state, isLoading: false, error: action.error};
        default:
            return state;
    }
}

const initialContractState = {
    contract: null,
    isLoading: false,
    error: null,
}

function contract(state = initialContractState, action) {
    switch(action.type) {
        case 'CREATE_CONTRACT_STARTED':
            return {...state, isLoading: true};
        case 'CREATE_CONTRACT_SUCCEEDED':
            return {...state, contract: action.contract, isLoading: false};
        case 'CREATE_CONTRACT_FAILED':
            return {...state, isLoading: false, error: action.error};
        default:
            return state;
    }
}

const initialWalletState = {
    account: null,
    balance: 0,
    isLoading: false,
    error: false
}

function wallet(state = initialWalletState, action) {
    switch(action.type) {
        case 'SET_WALLET_ADDRESS':
            return {...state, address: action.address};
        case 'CONNECT_WALLET_STARTED':
            return {...state, isLoading: true};
        case 'CONNECT_WALLET_SUCCEEDED':
            return {...state, account: action.account, isLoading: false};
        case 'CONNECT_WALLET_FAILED':
            return {...state, isLoading: false, error: action.error};
        case 'GET_BALANCE_STARTED':
            return {...state, isLoading: true};
        case 'GET_BALANCE_SUCCEEDED':
            return {...state, balance: action.balance, isLoading: false};
        case 'GET_BALANCE_FAILED':
            return {...state, isLoading: false, error: action.error};
        default: 
            return state;
    }
}

const reducers = combineReducers({
    web3,
    contract,
    wallet
});

export function getWeb3(state) {
    return state.web3.web3;
}

export function getWeb3IsLoading(state) {
    return state.web3.isLoading;
}

export function getWeb3Error(state) {
    return state.web3.error;
}

export function getContract(state) {
    return state.contract.contract;
}

export function getContractIsLoading(state) {
    return state.contract.isLoading;
}

export function getContractError(state) {
    return state.contract.error;
}

export function getWalletAddress(state) {
    return state.wallet.address;
}

export function getWalletAccount(state) {
    return state.wallet.account;
}

export function getWalletBalance(state) {
    return state.wallet.balance;
}

export function getWalletIsLoading(state) {
    return state.wallet.isLoading;
}

export function getWalletError(state) {
    return state.wallet.error;
}

export default reducers;