import React, { Component } from 'react';

import backend from 'lib/backend';
import qs from 'query-string';

export async function connectAccount(account, options) {
    try {
        let { body } = await backend(`/api/oauth2/client/auth`);
        if (body.url) {
            window.location.href = body.url;
        }
    } catch (e) {
        console.error(e);
    }
}

export async function authorizeCallback(body, options) {
    try {
        let response = await backend(`/api/oauth2/client/auth`, "PUT", { body: { ...body, ownerId: window.cfg.unitId, service: "google" } });
        window.location.href = "/settings/linked";
    } catch (e) {
        console.error(e);
    }
}


export function authCallbackRoute(options) {
    return {
        path: '/oauth2/client/callback',
        component: (props) => {
            let params = qs.parse(props.location.search);
            authorizeCallback(params);
            return <div>Please wait...</div>;
        }
    }
}