package user.person;

import common.Constant;
import user.common.AddressBind;
import user.common.AddressStatus;
import user.common.BindQuery;
import user.common.BindQueryResp;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class Test {

    public static void main(String[] args) throws Exception {
        RegisterPerson ps = new RegisterPerson("樊友祥", "123456789@qq.com", "17362878097", "429005199911300039", 1);

        AddressBind bd = new AddressBind(ps.register());

        ArrayList<String> list = new ArrayList<>();
        String address = bd.addressBind();
        list.add(address);

        String address1 = bd.addressBind();
        list.add(address1);

        List<AddressStatus> addressStatuses = waitingBind(list);
        System.out.println(addressStatuses);
    }

    public static List<AddressStatus> waitingBind(List<String> addressList) throws Exception {
        List<AddressStatus> resp = new ArrayList<>();
        BindQuery bq = new BindQuery(addressList);

        Duration timeout = Duration.ofMillis(Constant.DEFAULT_TIMEOUT);
        long timeBegin = System.currentTimeMillis();

        while (!bq.getAddressList().isEmpty() && Duration.between(
                Instant.ofEpochMilli(timeBegin),
                Instant.now()).compareTo(timeout) <= 0) {
            BindQueryResp bindQueryResp = bq.bindQuery();

            // 收集已经成功或失败的地址 todo 这里已经成功或失败的应该持久化
            resp.addAll(bindQueryResp.getList().stream()
                    .filter(addressStatus -> addressStatus.getStatus() == 2 || addressStatus.getStatus() == 3)
                    .collect(Collectors.toList()));

            // 查询条件过滤成功或者失败的情况
            List<String> addressList1 = bindQueryResp.getList().stream()
                    .filter(addressStatus -> addressStatus.getStatus() == 1 || addressStatus.getStatus() == 4)
                    .map(AddressStatus::getAddress)
                    .collect(Collectors.toList());

            bq.setAddressList(addressList1);

            // 等待一段时间再去查询
            TimeUnit.SECONDS.sleep(1);
        }

        // todo 日志打印超时后绑定中/未绑定的案例
        System.out.println(bq.getAddressList());

        return resp;
    }
}
