package GithubApi

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"strings"
	"time"
)

func SearchIssues(terms []string, queryDate int, appendArgs string) (*IssuesSearchResult, error) {
	// 指定查询日期
	var resTime = time.Now()
	const layout = "2006-01-02"                        // 确定 日期格式化样本
	resTime = resTime.AddDate(0, 0, -(queryDate))      // 确定查询后日期
	finalDate := " created:>" + resTime.Format(layout) // 拼接参数
	fmt.Println(finalDate)

	// 处理查询主体
	q := strings.Join(terms, " ")
	q += finalDate
	q = url.QueryEscape(q) + appendArgs
	fmt.Println(IssuesURL + "?q=" + q)
	resp, err := http.Get(IssuesURL + "?q=" + q)
	if err != nil {
		return nil, err
	}

	// We must close resp.Body on all execution paths.
	// (Chapter 5 presents 'defer', which makes this simpler.)
	if resp.StatusCode != http.StatusOK {
		err := resp.Body.Close()
		if err != nil {
			return nil, err
		}
		return nil, fmt.Errorf("search query failed: %s", resp.Status)
	}

	var result IssuesSearchResult
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		err := resp.Body.Close()
		if err != nil {
			return nil, err
		}
		return nil, err
	}
	err = resp.Body.Close()
	if err != nil {
		return nil, err
	}
	return &result, nil
}

func CategoryOutput(res *IssuesSearchResult) {
	const layout = "2006-01-02 15:04:05"
	// 时间
	now := time.Now()
	lastDayDate := now.AddDate(0, 0, -1)
	last7DayDate := now.AddDate(0, 0, -7)
	last30DayDate := now.AddDate(0, 0, -30)

	var inADay []*Issue
	var in7Day []*Issue
	var in30Day []*Issue
	var largeThan30 []*Issue
	for _, item := range res.Items {
		Create := item.CreatedAt
		if Create.Before(last30DayDate) {
			// 大于30天
			largeThan30 = append(largeThan30, item)
		} else if Create.Before(last7DayDate) && (Create.After(last30DayDate)) {
			// 大于7天小于30天
			in30Day = append(in30Day, item)
		} else if Create.Before(lastDayDate) && (Create.After(last7DayDate)) {
			// 大于1天 小于7天
			in7Day = append(in7Day, item)
		} else {
			// 1天以内
			inADay = append(inADay, item)
		}
	}
	fmt.Printf("%d issues:\n", res.TotalCount)
	if *IsCategory {
		fmt.Println("一天以内:")
		for _, item := range inADay {
			fmt.Println(item.CreatedAt.Format(layout), item.Title)
		}
		fmt.Println("7天以内:")
		for _, item := range in7Day {
			fmt.Println(item.CreatedAt.Format(layout), item.Title)
		}
		fmt.Println("30天以内:")
		for _, item := range in30Day {
			fmt.Println(item.CreatedAt.Format(layout), item.Title)
		}
		fmt.Println("30天以外:")
		for _, item := range largeThan30 {
			fmt.Println(item.CreatedAt.Format(layout), item.Title)
		}
	} else {
		for _, item := range res.Items {
			fmt.Printf("#%-5d %9.9s %.55s\n",
				item.Number, item.User.Login, item.Title)
		}
	}
}
