package utils

import (
	"bufio"
	"os"
	"strings"
    "io/ioutil"
	"net/http"
    "fmt"
    "github.com/cesanta/docker_auth/auth_server/authz"
    "encoding/json"
    "bytes"
)

const SuccessExitCode  =  0
const ErrorExitCode  = 1

// Read Standard input stream
func ReadStdIn() string {
	reader := bufio.NewReader(os.Stdin)
	text, _ := reader.ReadString('\n')
	text = strings.Replace(text, "\n", "", -1) // remove "\n" from the string.
	return text
}

// Check whether the array contains the given key
// This method is only efficient for arrays with smaller number of elements
func ArrayContains(array []string, key string) bool {
	for _, tmp := range array {
		if tmp == key {
			return true
		}
	}
	return false
}

func HttpLogin(username string, password string) (bool, error) {
    client := &http.Client{}

    loginUrl := "https://www.cloudam.cn/uaa/oauth/token?scope=ui&grant_type=password&username=" + username + "&password=" + password

    req, err := http.NewRequest("POST", loginUrl, nil)

    if err != nil {
        // handle error
    }

    req.Header.Set("authorization", "Basic YnJvd3Nlcjo=")

    resp, err := client.Do(req)

    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }
    if resp.StatusCode != 200 {
        return false, nil
    }
    fmt.Println(string(body))

    return true, nil
}

func HttpAuth(authReqInfo authz.AuthRequestInfo) bool {
    client := &http.Client{}
    authUrl := "http://47.57.4.97/c3ce/dockerimage/authorization"
    bytesData, _ := json.Marshal(authReqInfo)
    req, _ := http.NewRequest("POST", authUrl, bytes.NewReader(bytesData))

    req.Header.Set("authorization", "Basic 698c05d4-1f53-4ecd-a36c-82dc705086bd")

    resp, _ := client.Do(req)
    defer resp.Body.Close()

    body, _ := ioutil.ReadAll(resp.Body)
    if resp.StatusCode == 200 {
        return bool(string(body))
    }
    fmt.Println(string(body))
    return false
}
