package oauth2client

import (
	"errors"
	"local/oauth2"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"
)

func Authenticate(server string, w http.ResponseWriter, r *http.Request) error {
	oauth2server, err := url.Parse(server)
	if err != nil {
		return err
	}
	access, err := r.Cookie(oauth2.COOKIE)
	if err == http.ErrNoCookie {
		return login(oauth2server, w, r)
	}
	return verify(access.Value, oauth2server, w, r)
}

func login(oauth2server *url.URL, w http.ResponseWriter, r *http.Request) error {
	oauth2server.Path = "/users/log"
	url := *r.URL
	url.Host = r.Host
	if url.Scheme == "" {
		url.Scheme = "http"
	}
	cookie := &http.Cookie{
		Name:  oauth2.REDIRECT,
		Value: url.String(),
	}
	http.SetCookie(w, cookie)
	http.Redirect(w, r, oauth2server.String(), http.StatusSeeOther)
	return errors.New("logging in")
}

func verify(access string, oauth2server *url.URL, w http.ResponseWriter, r *http.Request) error {
	oauth2server.Path = "/verify"
	data := url.Values{}
	data.Set("access", access)
	req, err := http.NewRequest("POST", oauth2server.String(), strings.NewReader(data.Encode()))
	if err != nil {
		return err
	}
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
	c := &http.Client{
		Timeout: 5 * time.Second,
	}
	resp, err := c.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return login(oauth2server, w, r)
	}
	return nil
}
