package utils

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

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)
    fmt.Println(string(bytesData))
    req, _ := http.NewRequest("POST", authUrl, bytes.NewReader(bytesData))

    req.Header.Set("Content-Type", "application/json")
    resp, _ := client.Do(req)
    defer resp.Body.Close()

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