package ru.yandex.webmaster3.coordinator.http.feeds;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import lombok.RequiredArgsConstructor;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.Duration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.feeds.feed.NativeFeedInfo2;
import ru.yandex.webmaster3.core.http.Action;
import ru.yandex.webmaster3.core.http.ActionRequest;
import ru.yandex.webmaster3.core.http.ActionResponse;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.core.util.RetryUtils;
import ru.yandex.webmaster3.storage.feeds.FeedsNative2YDao;
import ru.yandex.webmaster3.storage.feeds.FeedsService;


/**
 * @author kravchenko99
 * @date 9/3/21
 */

@Component("/feeds/parseUrl")
@WriteAction
@Slf4j
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class ParseUrlMbiAction extends Action<ParseUrlMbiAction.Req, ParseUrlMbiAction.Res> {

    public static final RetryUtils.RetryPolicy linearPolicy = RetryUtils.linearBackoff(3, Duration.standardSeconds(15));

    private final FeedsNative2YDao feedsNativeYDao;
    private final FeedsService feedsService;

    @Override
    public Res process(Req request) throws WebmasterException {
        record X(String domain, URL url, NativeFeedInfo2 info){}
        List<X> l = new ArrayList<>();
        feedsNativeYDao.forEach(info -> {
            URL url = canonizeUrl(info.getUrl());
            if (url.getUserInfo() != null) {
                l.add(new X(info.getDomain(), url, info));
            }
        });

        l.forEach(x -> {
            String domain = x.domain();
            URL url = x.url();
            var info = x.info();
            FeedsService.UrlWithUserInfo urlWithUserInfo = feedsService.parseUrl(url);
            NativeFeedInfo2 build = info.toBuilder()
                    .url(urlWithUserInfo.url())
                    .login(urlWithUserInfo.login())
                    .password(urlWithUserInfo.password())
                    .build();
            feedsNativeYDao.update(build);
            feedsNativeYDao.remove(domain, url.toString());
        });

        return new Res();
    }


    public static URL canonizeUrl(String requestUrl) {
        try {
            return new URL(requestUrl);
        } catch (MalformedURLException e) {
            throw new IllegalStateException(e);
        }
    }

    public static class Req implements ActionRequest {
    }

    @Value
    public static class Res implements ActionResponse.NormalResponse {

    }
}
