/**
 * license: GPLv3
 * lodge.reservationsystem
*/
package lodge.reservationsystem;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;

import lodge.data.Account;
import lodge.data.AccountList;
import lodge.data.Address;
import lodge.data.EmailAddress;
import lodge.reservation.Reservation;
import lodge.reservation.IReservation;

public final class AccomodationManager {

    private final AccountList accounts = new AccountList();

    @SuppressWarnings("unused")
    private AccomodationManager() {
    };

    public AccomodationManager(String home) {

        setDataStoreRoot(home);
    };

    public final void setDataStoreRoot(String home) {
        DataRepository.setDataStoreRoot(home);
    }

    public final void loadAll() throws Exception {
        accounts.clear();
        // walk directories
        Path rootDir = Paths.get(DataRepository.getPath());
        DataRepository.WalkFileSystemTree(this, rootDir);
        System.out.println(String.format("%s LoadAll Accounts %d", "Deserializing", accounts.size()));
    }

    // Load / Deserialize Account
    public void load(Path file) throws Exception {
    
        Account account = DataRepository.LoadAccount(file);
        if (account == null) {
            System.out.println(String.format("%s", file.toString()));
        } else {
            accounts.add(account);
        }
    }

    public final List<Account> retrieveLoadedAccounts() {
        return Collections.unmodifiableList(accounts);
    }

    public Account retrieveAccount(String acct_id) {
        return accounts.find(acct_id);
    }

    public synchronized void AddAccount(final Account acct) throws Exception {
        accounts.add(acct);
    }

    public synchronized void UpdateAccount(final Account acct) throws Exception {
        if( acct != null ){
            accounts.save(acct);
        }
    }

    public final Account newAccount(String phone_number, Address mailing_address, EmailAddress email_address)
            throws Exception {
        Account acct = null;
        try {
            acct = new Account(phone_number, mailing_address, email_address);
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        accounts.save(acct);
        return acct;
    }

    public boolean addReservation(final Account account, final Reservation reservation){
        boolean result = account.add(reservation);
        return result;
    }

    public final Reservation findReservation(String reservation_number) {
        Reservation rsrv = null;
        for (Account acct : accounts) {
            rsrv = acct.findReservation(reservation_number);
            if( rsrv!=null ) break;
        }
        return rsrv;
    }

    public List<? extends IReservation> getReservationList() {
        return accounts.getListOfReservations();
    }

    public void showReservationList() {
        accounts.showReservationList();
    }

}